sfn
sfn

Reputation: 403

Test suite failed to run import.meta.env.VITE_*

After adding the environment variable import.meta.env.VITE_* in my code, the tests with vue-test-utils started to fail, with the error:

Jest suite failed to run
error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node12', or 'nodenext'.

I have searched for some available fixes but none have worked so far.

EDIT

jest.config.js file:

module.exports = {
  preset: "ts-jest",
  globals: {},
  testEnvironment: "jsdom",
  transform: {
    "^.+\\.vue$": "@vue/vue3-jest",
    "^.+\\js$": "babel-jest"
  },
  moduleFileExtensions: ["vue", "js", "json", "jsx", "ts", "tsx", "node"],
  moduleNameMapper: {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
      "<rootDir>/tests/unit/__mocks__/fileMock.js",
    "^@/(.*)$": "<rootDir>/src/$1"
  }
}

tsconfig.json file:

{
  "extends": "@vue/tsconfig/tsconfig.web.json",
  "include": ["env.d.ts", "src/**/*", "src/**/*.vue", "tests"],
  "compilerOptions": {
    "module": "esnext",
    "experimentalDecorators": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  },

  "references": [
    {
      "path": "./tsconfig.vite-config.json"
    }
  ]
}

When including module: "esnext", the warning below is displayed and the error remains.

Validation Warning:

Unknown option "module" with value "commonjs" was found. This is probably a typing mistake. Fixing it will remove this message.

Configuration Documentation: https://jestjs.io/docs/configuration

Upvotes: 22

Views: 28225

Answers (4)

nstanard
nstanard

Reputation: 823

Personally I route all my import.meta.env values through a single file (src/constants.ts or src/constants.js)

// src/constants.(js|ts)...

const {
  MODE: ENVIRONMENT,
} = import.meta.env;

export {
  ENVIRONMENT
};

Then in my jest tests I just mock the constants file:

// example.test.(js|ts)
jest.mock('src/constants', () => ({
  ENVIRONMENT: 'development',
}));

IMHO this is better also because you'll likely want to mock the value anyway.

If you want to mock things at the global level you can do what @FahadJaved talks about in the comments. It would look something like this:

// jest.config.(js|ts)
moduleNameMapper: {
    // other things...
    'src/constants': '<rootDir>/__mocks__/constantsMock.ts',
  },
// __mocks__/constantsMock.ts

export const ENVIRONMENT = 'development';

// or... 

jest.mock('src/constants', () => ({
  ENVIRONMENT: 'development',
}));

Just be sure your imports always use the exact path that gets mocked, src/constants. You may have to configure tsconfig.json to allow always using src/constants in your imports (no relative paths with ../, etc.).

    "compilerOptions": {
        "baseUrl": "./",
        "paths": {
            "src/*": ["src/*"]
        },
        // ...
    },
    // ...

Upvotes: 40

Istv&#225;n Zsigovics
Istv&#225;n Zsigovics

Reputation: 29

Hey I just went through the same problem and I realised that the problem was that the tests were using files what was importing the file that contained something similar:

        const {
      MODE: ENVIRONMENT,
    } 

= import.meta.env; 

So the solution is to import this variable into those test files like:

    jest.mock('../your/envConstants.ts', () => ({
  MODE: 'YOUR_MODE',
}));

This solved me the problem...

Upvotes: -1

Maximiliano Santana
Maximiliano Santana

Reputation: 11

If you are using react + vite, I tried the following:

npm install --save-dev dotenv cross-env

to get env in standard form, then I made the following configuration in my vite.config.js

...
import { loadEnv } from 'vite'
...
export default defineConfig(({ command, mode }) => { 
  const env = loadEnv(mode, process.cwd(), '');
  return {
    plugins:[react()],
    server: {
      host:true
    },
    define: {
      'process.env.YOUR_STRING_VARIABLE': 
      JSON.stringify(env.YOUR_STRING_VARIABLE),
      'process.env.APP_USE_AVT': env.APP_USE_AVT,
    },
  };
});

this solved it.

Upvotes: 1

sfn
sfn

Reputation: 403

After much research, I was able to solve the case.

I had to install the vite-plugin-environment and babel-plugin-transform-import-meta libraries and make the following settings:

babel.config.js

module.exports = {
  ...
  plugins: ["babel-plugin-transform-import-meta"]
}

tsonfig.json

{
  ...
  "compilerOptions": {
    "module": "esnext",
    ...
    "types": [
      "node"
    ]
  },
  ...
}

vite.config.ts

...
import EnvironmentPlugin from "vite-plugin-environment"
...
export default defineConfig({
  plugins: [..., EnvironmentPlugin("all")],
  ...
})

Also change the import.meta.env.* to process.env.*

Upvotes: 12

Related Questions