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