Jest - SyntaxError: Cannot use import statement outside a module

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


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',
}