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"

Leave a Comment