How to resolve "Cannot use import statement outside a module" in jest
Solution 1
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"
Solution 2
Use Babel to transpile those JS Modules and you'll be able to write your tests with es6.
Install Babel/preset-env
npm i -D @babel/preset-env
Create a babel configuration file with the preset
//babel.config.js
module.exports = {presets: ['@babel/preset-env']}
Solution 3
I solved this by migrating the .babelrc
file to babel.config.js
! Shocker.
Solution 4
try this thing if you are using babel 6
- Adding
@babel/plugin-transform-modules-commonjs
in the plugin section ofbabel.config.js
or
- For my case import issue was due to the react file drop by adding that to
transformIgnorePatterns
"transformIgnorePatterns": ["/node_modules/(?!react-file-drop)"]
Solution 5
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.
Logan Shoemaker
Front-end developer experienced in JavaScript (React), HTML, and CSS. Likes: consistency and readability in code Dislikes: unnecessary bloat and inconsistency in code
Updated on January 21, 2022Comments
-
Logan Shoemaker over 2 years
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 have tried removing all packages and re-adding them. It does not resolve this. I have looked at similar questions and documentation and I am still misunderstanding something. I went so far as to follow another guide for setting up this environment from scratch and still received this issue with my code.
Dependencies include...
"dependencies": { "@babel/plugin-transform-runtime": "^7.6.2", "@babel/polyfill": "^7.6.0", "babel-jest": "^24.9.0", "react": "^16.8.6", "react-dom": "^16.8.6", "react-test-renderer": "^16.11.0", "source-map-loader": "^0.2.4" }, "devDependencies": { "@babel/core": "^7.6.0", "@babel/preset-env": "^7.6.0", "@babel/preset-react": "^7.0.0", "@types/enzyme": "^3.9.2", "@types/enzyme-adapter-react-16": "^1.0.5", "@types/jest": "^24.0.13",
The component's import lines...
import * as React from "react"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import HomePage from "./components/pages"; import { Footer, Header, Navigation, } from "./components/shared";
The test file....
import * as React from "react"; import * as renderer from "react-test-renderer"; import App from "../App"; it("Renders the Footer correctly", () => { const tree = renderer .create(<App />) .toJSON(); expect(tree).toMatchSnapshot(); });
I expected to be able to use named imports in my components without my tests blowing up. It appears to fix the issue if I only use default imports through my solution, but I would prefer to not go that route.
-
Nida Munir about 4 yearsWhat did you change?
-
Jianwu Chen about 4 yearsSorry for the mistake in my original post. I was using es6 in the dependent module. That's the root cause of the problem. After I changed back to es5, the problem is solved
-
Teodor Ciuraru about 4 yearsHow did you solve the problem with the
index.js
in other modules? -
Ryall almost 4 yearsThis was my issue! Forgot to copy over the babel config! Thanks :)
-
Jason R Stevens CFA over 3 yearsDirect and concise, thank you! For my project derived on
tsdx
this was the trick (along with@babel/preset-react
). -
Steph M over 3 yearsThank you! This worked like a charm. Had to convert my .babelrc to a babel.config.js to do this but it all worked out!
-
Vipul Dessai over 3 yearsfor me, the new transform for typescript files was giving problem, solved by adding js transform to use the babel-jest i.e adding "^.+\\.(js|jsx)$": "babel-jest" to transform in jest config js file
-
Tomas Dermisek about 3 yearsIn my case, helped only
transformIgnorePatterns: ['/node_modules/(?!react-hls-player)'],
-
ZAD almost 3 yearsMy Jest config was only missing moduleDirectories: ["node_modules", "src"], of which I added and everything start working as expected. Thank you
-
Moso Akinyemi almost 3 yearsWorks, don't forget to also install
@babel/preset-env
😉 -
Victor Karangwa almost 3 yearsThank you, this resolved the issue on my end
-
aldenn over 2 yearsI spend two hours resolving this error. And well, after reading this answer, I want to cry right now T_T. I'm migrating from js to typescript and I forgot to rename ".js" to ".ts"
-
Nick Taras over 2 yearsThanks so much, this was causing me a lot of trouble too, your solution took seconds to include and like others have said - it works like charm.
-
guero64 over 2 years
npm i -D @babel/preset-env
gave me an error. Needednpm i --save-dev @babel/preset-env
-
Fabien Salles over 2 yearsThanks, I'm also suprised that nobody upvote your answer soon, but you solved my problem !
-
Juan David Robles about 2 yearsThis worked for me. Setting
preset: 'ts-jest'
injest.config.js
was key -
Akber Iqbal almost 2 yearsi have this issue with a dependency of a dependency; had to add
transformIgnorePatterns: ["/node_modules/(?!formidable)"]
injest.config.ts
on top of the steps above -
Steve Bennett almost 2 yearsWow, step 1 solved the problem for me, using Babel 7. Amazing. So many possible solutions here, but this was the one that did it for me.
-
skladany almost 2 yearsThis works perfectly! (Just note that you *cannot* be using
"type": "module",
in yourpackage.json
if you go this route.)