Search code examples
reactjstestingjestjsviteesbuild

Testing React app with Jest, using Vite as a module Bundler; import.meta error


i am testing a React-Typescript application with Jest; my application uses Vite as a module bundler. The issue is, everytime i run tests and jest encounters an import.meta.ENV_VAR_NAME statement i get the following error: "SyntaxError: Cannot use 'import.meta' outside a module"

This is my jest.config.js file:

module.exports = {
roots: ["<rootDir>/src"],
setupFilesAfterEnv: ["<rootDir>/jest/jest.setup.js"],
collectCoverageFrom: ["src//*.{js,jsx,ts,tsx}", "!src//.d.ts"],
testMatch: [
    "<rootDir>/src//tests//.{js,jsx,ts,tsx}",
    "<rootDir>/src/*/.{spec,test}.{js,jsx,ts,tsx}"
],
testEnvironment: "jsdom",
transform: {
    // "^.+\.(js|jsx|mjs|cjs|ts|tsx)$": "esbuild-jest",
    "^.+\.(js|jsx|mjs|cjs|ts|tsx)$": "@swc/jest",
    "^.+\.scss$": "jest-scss-transform",
    "^.+\.css$": "<rootDir>/jest/mocks/cssMock.js"
},
transformIgnorePatterns: [
    "[/\\]node_modules[/\\].+\.(js|jsx|mjs|cjs|ts|tsx)$",
    "^.+\.module\.(css|sass|scss)$"
],
watchPlugins: [
    "jest-watch-typeahead/filename",
    "jest-watch-typeahead/testname"
],
resetMocks: true,
moduleDirectories: ["node_modules", "src"],
moduleNameMapper: {
    "\.worker": "<rootDir>/src/seo/mocks/workerMock.ts",
    "\.(css|sass|scss)$": "identity-obj-proxy"
}
};

In transform key of jest.config i tried using either @swc/jest and esbuild-jest, but none fixed the import.meta issue; is there a solution to this problem? Can i achieve it without using Babel?

Thanks in advance for your time


Solution

    • https://codingwithmanny.medium.com/quick-jest-setup-with-vitejs-react-typescript-82f325e4323f
    • refer the above link for setting up Jest in your Vite project.
    • install this plugin (https://www.npmjs.com/package/vite-plugin-environment)
    • create .env file in your project root folder near package.json
    • provide your env variables in .env files
    • change all your import.meta.env.YOUR_VAR to process.env.YOUR_VAR
    • open vite.config.ts and import import EnvironmentPlugin from 'vite-plugin-environment';
    • add EnvironmentPlugin('all') in plugins. example: plugins: [react(), EnvironmentPlugin('all')]
    • now your test will pass without import.meta.env error.
    • the explanation behind this config is that Jest will understand process.env.YOUR_VAR, so if you change all your import.meta.env.YOUR_VAR to process.env.YOUR_VAR then Jest will not give error.
    • But then we have to provide vite-plugin-environment to Vite Config so that it understands process.env.YOUR_VAR
    • it works in production as well.