75

I am using jest:24.9.0 without any configuration, installed globally from a create-react-app. Inside these files I am using es6 modules. There is no error when using "test": "react-scripts test"

However when I move to use jest with "test": "jest --config jest.config.js", I see the below error.

 FAIL  src/configuration/notifications.test.js
  ● Test suite failed to run

    /var/www/management/node/src/configuration/notifications.test.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import notifications from './notifications';
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module
0

8 Answers 8

73

Jest doesn't support ES6 module and hence throwing this error when you directly run the test with Jest. If you want to run like that then you have to add babel.

On the other side, when you run the test with react-scripts it uses babel behind the scene to transpile the code.

In newer version of jest, babel-jest is now automatically loaded by Jest and fully integrated

Hope this answer your question.

Adding babel in jest.

Installation

babel-jest is now automatically loaded by Jest and fully integrated. This step is only required if you are using babel-jest to transform TypeScript files.

npm install --save-dev babel-jest

Usage

In your package.json file make the following changes:

{
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "transform": {
      "^.+\\.[t|j]sx?$": "babel-jest"
    }
  }
}

Create babel.config.json configuration file

Create a babel.config.json config in your project root and enable some presets.

To start, you can use the env preset, which enables transforms for ES2015+

npm install @babel/preset-env --save-dev

In order to enable the preset you have to define it in your babel.config.json file, like this:

{
  "presets": ["@babel/preset-env"]
}

Check for more details on Babel official site

Sign up to request clarification or add additional context in comments.

11 Comments

How do you "add babel"?
NB that .babelrc doesn't work you have to name it babel.config.json
I had to npm install regenerator-runtime and also import 'regenerator-runtime/runtime' at the top of my testfile
@GunarGessner is there a particular reason why .babelrc doesnt work?
@blu10 it just didn't work for me I guess
|
22

As answers above have described, Jest doesn't support ES6 modules. So, we need transform the code to a supported module type. We could use babel-jest or ts-jest. I recommend using ts-jest for simplicity.

Step 1: installation:

npm i -D ts-jest @types/jest or yarn add --dev ts-jest @types/jest

Step 2: Configuration

Option 1: create a jest configration file jest.config.js

module.exports = {
    transform: {
        '^.+\\.(ts|tsx)$': 'ts-jest',
    },
};

Option 2: add jest configuration into package.json

"jest": {
    "transform": {
        "^.+\\.(ts|tsx)$": "ts-jest"
    }
}

Step 3: Execute your script. Everything should be all set now.

1 Comment

OP didn't try to make it work for typescript
5

Since jest is not working with esmodules well, you need to add these configurations in jest.config.js to tell Jest to use commonJS builds instead

moduleNameMapper : {
        '^react-dnd$': 'react-dnd/dist/cjs',
        '^react-dnd-html5-backend$': 'react-dnd-html5-backend/dist/cjs',
        '^dnd-core$': 'dnd-core/dist/cjs',
}

1 Comment

This was what worked for me after trying multiple other solutions. Thanks a bunch!
3

The error

SyntaxError: Cannot use import statement outside a module

might also come from some imported library under node_modules, for example

...\node_modules\node-fetch\src\index.js:9
    import http from 'node:http';
    ^^^^^^

The trick for me was to use the transformIgnorePatterns option in jest config:

transformIgnorePatterns: [
    'node_modules/(?!' + 
        [
            'node-fetch',
            'fetch-blob',
            'data-uri-to-buffer',
            'jest-runtime',
            'formdata-polyfill'
        ].join('|') +
    ')',
],

Also see

How to setup jest with node_modules that use es6

2 Comments

This worked for me when I got the error on an import statement for the node module lucide-svelte. Thanks a bunch!
This one worked for me as well! But it might just be that node-fetch was only module I was importing from node_modules at the time.
0

When you are using Typescript with ECMAScript. The simplest solution is to use use ts-jest, a TypeScript preprocessor:

  1. Install
npm i -D ts-jest @types/jest
  1. Run tests
jest

npm, github

Comments

0

I received this same error using react-scripts to run tests. I was able to resolve this issue by changing the line in package.json

"test": "react-scripts test",

to

"test": "NODE_OPTIONS=--experimental-vm-modules react-scripts test",

From the error message which provides the link that suggests this resolution:

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.

Comments

0

I wanted to add how I easily caused this issue for myself.. I freaking prevented myself from committing my jest.config.js file by including all *.js in my .gitignore. Every time my CI ran, I would get this error, because there was no version controlled jest.config.js in my repo. Be careful out there folks! stay frosty.

1 Comment

What did you put in your jest.config.js to avoid the "Cannot use import statement outside a module" error?
0

This issue has a long discussion in the source package with some alternative solutions https://github.com/kulshekhar/ts-jest/issues/1174.

The solution that worked for me, using Typescript, ES6 modules, and jest was using the package ts-jest-mock-import-meta

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.