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

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


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"


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.jsmodule.exports = {presets: ['@babel/preset-env']}


I solved this by migrating the .babelrc file to babel.config.js! Shocker.