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
.env file in your project root folder near package.json.env filesimport.meta.env.YOUR_VAR to process.env.YOUR_VARvite.config.ts and import import EnvironmentPlugin from 'vite-plugin-environment';EnvironmentPlugin('all') in plugins. example: plugins: [react(), EnvironmentPlugin('all')]import.meta.env error.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.vite-plugin-environment to Vite Config so that it understands process.env.YOUR_VAROR! You could just mock the env vars in your Jest context. Much simpler.
(this is already answered on another SO post) Test suite failed to run import.meta.env.VITE_*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With