aelbore / esbuild-jest

A Jest transformer using esbuild
519 stars 51 forks source link

Usage with `import.meta.env` #60

Open harrygr opened 2 years ago

harrygr commented 2 years ago

I'm using this package in my Jest setup in a Vite project.

With es modules env variables are accessed through import.meta.env. When I run my Jest tests, any that import a module that involves accessing an env variable results in the following error:

TypeError: Cannot read property 'VITE_MY_ENV_VAR' of undefined

Suggesting that import.meta.env is undefined; although import.meta looks to be defined or the error would say so.

Any idea how to solve this?

Joshuabaker2 commented 2 years ago

For any future people coming here, I solved this by grabbing the changes at https://github.com/aelbore/esbuild-jest/pull/56, patching my local version of esbuild-jest to match, and then doing:

"jest": {
    "transform": {
      "^.+\\.(js|ts)x?$": [
        "esbuild-jest",
        {
          "define": {
            "import.meta.env": "{}"
          }
        }
      ]
    }
}

In my package.json