How to resolve “Cannot use import statement outside a module” from Jest when running tests?

I was having the same failure (also using Babel, Typescript and Jest), it was driving me crazy for hours!

Ended up creating a new babel.config.js file specifically for the tests. I had a large .babelrc that wasn’t getting picked up by jest no matter what I did to it. The main app still uses the .babelrc as this overrides babel.config.js files.

Steps I took:

Install jest, ts-jest and babel-jest:

npm i jest ts-jest babel-jest

Add babel.config.js (only used by jest)

module.exports = {presets: ['@babel/preset-env']}

In jest.config.js update to:

module.exports = {
  preset: 'ts-jest',
  transform: {
    '^.+\\.(ts|tsx)?$': 'ts-jest',
    "^.+\\.(js|jsx)$": "babel-jest",
  }
};

package.json

  "scripts": {
    "test": "jest"

Leave a Comment