To fix Jest ‘encountered an unexpected token import’ error with JavaScript, we set the Jest config to allow modules.
For instance, in jest.config.js, we write
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["./src"],
transform: { "\\.ts$": ["ts-jest"] },
testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
globals: {
"ts-jest": {
tsConfig: {
allowJs: true,
},
},
},
};
to allow extensions for modules by setting moduleFileExtensions
to ["ts", "tsx", "js", "jsx", "json", "node"]
.
We set allowJs
to true
to allow JavaScript code to run including modules.
And we set transform
to { "\\.ts$": ["ts-jest"] }
to transform them with ts-jest so they can be run with Jest.