React Jest test fails to run with ts-jest - Unexpected token on imported file
After messing around with this for absolutely ages it looks like the problem was to do with the lodash-es package and Jest not supporting ES modules. This is mentioned here: https://github.com/facebook/jest/issues/4842
Using @CarlosCrespo answer as a basis I also had to tell babel not to ignore lodash-es when transpiling using the transformIgnorePatterns
property to give me the following:
jest.config.js
module.exports = { moduleDirectories: [ 'node_modules' ], transform: { "\\.tsx?$": "ts-jest", "\\.jsx?$": "babel-jest", // if you have jsx tests too }, globals: { "ts-jest": { "tsConfig": '<rootDir>/tsconfig.json' } }, transformIgnorePatterns: [ "[/\\\\]node_modules[/\\\\](?!lodash-es/).+\\.js$" ],}
In addition to this I also needed to update my tsconfig.json after another error - Cannot read property createElement of undefined
was caused whilst using TypeScript: https://github.com/testing-library/react-testing-library/issues/374
tsconfig.json
{ "compilerOptions": { "outDir": "./dist/", "noImplicitAny": true, "lib": ["dom", "esnext"], "module": "esnext", "target": "es5", "jsx": "react", "esModuleInterop": true, "allowJs": true, "allowSyntheticDefaultImports": true }, "exclude": ["node_modules"]}
Looks like you have to add this to your Jest config file
"transform": { "\\.tsx?$": "ts-jest", "\\.jsx?$": "babel-jest", // if you have jsx tests too},"globals": { "ts-jest": { "tsConfig": pathToYourTsConfigFile }}
more on that here: https://jestjs.io/docs/en/configuration.html#transform-object-string-pathtotransformer-pathtotransformer-object and here https://kulshekhar.github.io/ts-jest/user/config/
I've since discovered another alternative for the specific case of lodash-es. You can use the normal lodash library and just import the function you need. You can then get the benefit of the lodash-es package without needing to use transformIgnorePatterns.
E.g:
import camelCase from 'lodash/camelCase';camelCase('my string');