How to resolve "Cannot use import statement outside a module" in jest

117,622

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

  1. Adding @babel/plugin-transform-modules-commonjs in the plugin section of babel.config.js

or

  1. 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.

Share:
117,622
Logan Shoemaker
Author by

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, 2022

Comments

  • Logan Shoemaker
    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:

    jest 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
    Nida Munir about 4 years
    What did you change?
  • Jianwu Chen
    Jianwu Chen about 4 years
    Sorry 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
    Teodor Ciuraru about 4 years
    How did you solve the problem with the index.js in other modules?
  • Ryall
    Ryall almost 4 years
    This was my issue! Forgot to copy over the babel config! Thanks :)
  • Jason R Stevens CFA
    Jason R Stevens CFA over 3 years
    Direct and concise, thank you! For my project derived on tsdx this was the trick (along with @babel/preset-react).
  • Steph M
    Steph M over 3 years
    Thank 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
    Vipul Dessai over 3 years
    for 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
    Tomas Dermisek about 3 years
    In my case, helped only transformIgnorePatterns: ['/node_modules/(?!react-hls-player)'],
  • ZAD
    ZAD almost 3 years
    My Jest config was only missing moduleDirectories: ["node_modules", "src"], of which I added and everything start working as expected. Thank you
  • Moso Akinyemi
    Moso Akinyemi almost 3 years
    Works, don't forget to also install @babel/preset-env 😉
  • Victor Karangwa
    Victor Karangwa almost 3 years
    Thank you, this resolved the issue on my end
  • aldenn
    aldenn over 2 years
    I 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
    Nick Taras over 2 years
    Thanks 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
    guero64 over 2 years
    npm i -D @babel/preset-env gave me an error. Needed npm i --save-dev @babel/preset-env
  • Fabien Salles
    Fabien Salles over 2 years
    Thanks, I'm also suprised that nobody upvote your answer soon, but you solved my problem !
  • Juan David Robles
    Juan David Robles about 2 years
    This worked for me. Setting preset: 'ts-jest' in jest.config.js was key
  • Akber Iqbal
    Akber Iqbal almost 2 years
    i have this issue with a dependency of a dependency; had to add transformIgnorePatterns: ["/node_modules/(?!formidable)"] in jest.config.ts on top of the steps above
  • Steve Bennett
    Steve Bennett almost 2 years
    Wow, 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
    skladany almost 2 years
    This works perfectly! (Just note that you *cannot* be using "type": "module", in your package.json if you go this route.)