Search code examples
reactjstypescriptjestjsvitets-jest

Jest is giving error while using meta in import statement


I have a react application with Vite framework in which I want to write the test cases using Jest. But the issue is jest is unable to read import.meta

Restarted the TS server as well but still this issue exist.

Attaching tsconfig file and jest config file for reference.

tsconfig.json

    {
  "compilerOptions": {
    "target": "esnext",
    "lib": ["dom", "dom.iterable", "esnext"],
    "types": ["./types/fin", "./types/heap", "node", "jest", "vite/client", "vite-plugin-svgr/client"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": false,
    "jsx": "react-jsx",
    "noImplicitAny": false,
    "baseUrl": ".",
    "paths": {
      "src/*": ["src/*"]
    }
  },
  "include": ["src", "src/config/authConfig.ts"],
  "exclude": ["node_modules", "build"]
}

jest.config.js

module.exports = {
  preset: 'ts-jest',
  collectCoverage: true,
  collectCoverageFrom: ['./src/**'],
  testEnvironment: 'node',
  moduleNameMapper: { '^.+\\.(css|less|gif|jpg|jpeg|svg|png)$': 'module.exports = {};', 'src/(.*)': '<rootDir>/src/$1' },
};

Please have a look on the config files and suggest what can done in this.

Error:-

● Test suite failed to run

    src/helpers/envHelper.tsx:1:25 - error TS1343: The 'import.meta' meta- 
    property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 
    'system', 'node16', or 'nodenext'.

    export const NODE_ENV = import.meta.env.VITE_NODE_ENV;

Solution

  • Use this code in the .test file in order to mock the import statement for meta (import.meta)

    jest.mock('src/util/helpers/envVariableHelper.tsx', () => ({
      NODE_ENV: 'test',
      REACT_APP_BASE_URL: 'http://mocked-base-url',
    }));