I have a React application (not using Create React App) built using TypeScript, Jest, Webpack, and Babel. When trying to run \"yarn jest\", I get the following error:
I solved this by migrating the .babelrc
file to babel.config.js
! Shocker.
Use Babel to transpile those JS Modules and you'll be able to write your tests with es6.
npm i -D @babel/preset-env
//babel.config.js
module.exports = {presets: ['@babel/preset-env']}
Solution: my named imports were coming from index.js files and I believe ts-jest needed them as index.ts files (I'm using Typescript). If anyone else runs into this error, couldn't hurt to check if you derped your file extensions.
I wasted a lot of time on this, unfortunately, but I learned a lot about webpack configurations and Babel.
Also using Babel, Typescript and Jest. Had the same failure, driving me crazy for hours.
Ended up creating a new babel.config.js
file specifically for the tests. Had a large .babelrc
that wasn't getting picked up by jest no matter what i did to it. Main app still uses the .babelrc
as this overrides babel.config.js
files.
Install jest, ts-jest and babel-jest:
npm i jest ts-jest babel-jest
babel.config.js
(only used by jest)
module.exports = {presets: ['@babel/preset-env']}
jest.config.js
module.exports = {
preset: 'ts-jest',
transform: {
'^.+\\.(ts|tsx)?$': 'ts-jest',
"^.+\\.(js|jsx)$": "babel-jest",
}
};
package.json
"scripts": {
"test": "jest"
For future references,
I solved the problem by using below jest config, after reading Logan Shoemaker's answer.
module.exports = {
verbose: true,
setupFilesAfterEnv: ["<rootDir>src/setupTests.ts"],
moduleFileExtensions: ["js", "jsx", "ts", "tsx"],
moduleDirectories: ["node_modules", "src"],
moduleNameMapper: {
"\\.(css|less|scss)$": "identity-obj-proxy"
},
transform: {
'^.+\\.(ts|tsx)?$': 'ts-jest',
"^.+\\.(js|jsx)$": "babel-jest",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/file.js",
}
};
try this thing if you are using babel 6
1) Adding @babel/plugin-transform-modules-commonjs in the plugin section of babel.config.js
or
2) For my case import issue was due to the react file drop by adding that to transfromIgnorePatterns "transformIgnorePatterns": [ "/node_modules/(?!react-file-drop)" ],