jest: Error: SyntaxError: Cannot use import statement outside a module

I have this issue when I’m trying to run the tests with this configuration:

jest.config.js

module.exports = {
  verbose: true,
  preset: 'react-native-web'
}

babel.config.js

module.exports = {
  presets: [
    '@babel/react',
    [
      '@babel/preset-env',
      {
        targets: {
          esmodules: true,
        },
      },
    ],
  ],
  plugins: [
    '@babel/plugin-proposal-function-bind',
    '@babel/plugin-proposal-class-properties',
    '@babel/plugin-syntax-dynamic-import',
    [
      'module-resolver',
      {
        alias: {
          '^react-native$': 'react-native-web',
        },
      },
    ],
  ],
  env: {
    production: {
      plugins: [
        [
          'transform-react-remove-prop-types',
          {
            mode: 'remove',
            ignoreFilenames: ['node_modules'],
          },
        ],
      ],
    },
  },
}

Then, the error:

    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React from 'react'
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 145
  • Comments: 32

Commits related to this issue

Most upvoted comments

I solved the f***ing thing by migrating the .babelrc file to babel.config.js! Shocker.

In my configurations ts-jest + jest-puppeteer I added the following transform property to jest.config.js:

module.exports = {
  preset: 'jest-puppeteer',
  transform: {"\\.ts$": ['ts-jest']}
};

and this solved the issue

I am having this issue with @react-native-firebase/app v6

/.../node_modules/@react-native-firebase/app/lib/index.js:18
    import { getFirebaseRoot } from './internal/registry/namespace';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import firebase from '@react-native-firebase/app';
        | ^
      2 | import '@react-native-firebase/firestore';
      3 | import '@react-native-firebase/crashlytics';
      4 | 

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
      at Object.<anonymous> (src/config/rnFirebase.js:1:1)

My jest config is in the package.json as follows, could it be a problem?

{
  "scripts": {
    "postinstall": "jetify",
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "web": "expo start --web",
    "start": "react-native start",
    "test": "jest"
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.7.1",
    "@react-native-firebase/app": "^6.2.0",
    "@react-native-firebase/auth": "^6.2.0",
    "@react-native-firebase/crashlytics": "^6.2.0",
    "@react-native-firebase/firestore": "^6.2.0",
    "expo": "~36.0.0",
    "expo-asset": "^8.0.0",
    "expo-font": "^8.0.0",
    "expo-linear-gradient": "^8.0.0",
    "expo-location": "^8.0.0",
    "expo-permissions": "^8.0.0",
    "formik": "^2.0.8",
    "geofirestore": "^3.3.1",
    "geolib": "^3.2.0",
    "haversine": "^1.1.1",
    "js-sha256": "^0.9.0",
    "lodash": "^4.17.15",
    "moment": "^2.24.0",
    "moment-duration-format": "^2.3.2",
    "native-base": "^2.13.8",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "~0.61.4",
    "react-native-base64": "^0.0.2",
    "react-native-dotenv": "^0.2.0",
    "react-native-elements": "^1.2.7",
    "react-native-gesture-handler": "~1.5.0",
    "react-native-keyboard-aware-scroll-view": "^0.9.1",
    "react-native-maps": "^0.26.1",
    "react-native-maps-animated-polyline": "^1.0.6",
    "react-native-maps-super-cluster": "^1.6.0",
    "react-native-reanimated": "~1.4.0",
    "react-native-safe-area-context": "0.6.0",
    "react-native-safe-area-view": "^1.0.0",
    "react-native-scalable-image": "^1.0.0",
    "react-native-screens": "~2.0.0-alpha.12",
    "react-native-splash-screen": "^3.2.0",
    "react-native-svg": "^9.13.6",
    "react-native-unimodules": "~0.7.0",
    "react-native-web": "~0.11.7",
    "react-navigation": "^4.0.10",
    "react-navigation-drawer": "^2.2.2",
    "react-navigation-header-buttons": "^3.0.4",
    "react-navigation-stack": "^1.9.4",
    "react-navigation-tabs": "^2.5.6",
    "react-redux": "^7.1.1",
    "redux": "^4.0.4",
    "redux-thunk": "^2.3.0",
    "reselect": "^4.0.0",
    "throttle-debounce": "^2.1.0"
  },
  "devDependencies": {
    "@babel/core": "~7.6.0",
    "babel-jest": "~24.9.0",
    "jest": "~24.9.0",
    "jest-expo": "^36.0.0",
    "jetifier": "~1.6.4",
    "metro-react-native-babel-preset": "~0.56.0",
    "react-native-svg-transformer": "^0.14.3",
    "react-test-renderer": "~16.9.0",
    "redux-devtools-extension": "^2.13.8"
  },
  "jest": {
    "projects": [
      {
        "preset": "jest-expo/ios"
      },
      {
        "preset": "jest-expo/android"
      }
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|@react-native-firebase/.*|react-native-firebase)"
    ]
  },
  "private": true
}

What am I missing? I am new to unit testing so any help will be very much appreciated!!!

I wrote an article to sum up the solutions as i was unable to find a proper solution for the issue. Hope this will help https://xperimentalhamid.com/how-do-i/fix-cannot-use-import-statement-outside-a-module/

I’m having this problem I’ve never had before. What can I do.

screenshot 2020-04-06 a las 18 59 31

We enabled tests in a Heroku pipeline for one of our apps, and this error started popping up. I can’t replicate it locally, or in a Docker container (node 8 and LTS tested). I have no idea what’s causing this, and the fact that it only happens in my Heroku environment has me scratching my head even more.

UPDATE This turned out to be pretty specific to our codebase and having NODE_ENV set to production in our test environment. Heroku defaults to setting that to test but we were overriding that causing some problems. I doubt this will help future travelers who have the same problem. Godspeed!

and how can i solve this problem in a vue project using @vue/composition

module.exports = {
  preset: "@vue/cli-plugin-unit-jest/presets/typescript-and-babel",
  transformIgnorePatterns: [
    "/node_modules/(?!lib-to-transform|other-lib)",
    "./src/common/index.js",
  ]
};

it is my jest.config.js

What worked for me was changing the modules option of Babel’s ENV preset from false to auto.

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

I am having the same issue, i’m using CRA, don’t know what to do.

@lean’s StackOverflow link helped me solve this issue. Thanks!

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

Ditto 🤦‍♂️. I had to move over to a .babelrc for integration with parcel (they don’t support babel.config.js). Rather annoying that I am now going to have to have both for the time being…

I’m seeing this with crossfilter2 with jest unit tests.

/c/Users/newbe/play/edgauge/cvu-prototype-portal/node_modules/crossfilter2/src/index.js:1

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import xfilterArray from './array';
                                                                                         ^^^^^^

SyntaxError: Cannot use import statement outside a module

  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
  at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
  at node_modules/dc/src/footer.js:21:28
  at Object.<anonymous> (node_modules/dc/src/footer.js:35:1)

Using jest@24.9.0 from react-scripts@3.3.0 importing crossfilter2@1.5.0.

Update: I resolved my issue with crossfilter by upgrading to crossfilter 1.5.1 which changed it’s CommonJS entry point.

I still get the error. Any help please!

 FAIL  tests/topup-package/topup-package.spec.ts
  ● Test suite failed to run

    /home/fsevenm/nodejs-projects/deliverit/tests/test-environment.ts:1
    import NodeEnvironment from "jest-environment-node";
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at runTestInternal (node_modules/jest-runner/build/runTest.js:223:5)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.025 s
// test-environment.ts
import NodeEnvironment from "jest-environment-node";
import { createUser, destroyUsers } from "./utils";

class TestEnvironment extends NodeEnvironment {
  async setup(): Promise<void> {
    await super.setup();
    const { token } = await createUser();

    this.global.authToken = token;
  }

  async teardown(): Promise<void> {
    await destroyUsers();
    await super.teardown();
  }
}

export default TestEnvironment;
// jest.config.js
module.exports = {
  preset: "ts-jest",
  testEnvironment: "<rootDir>/tests/test-environment.ts",
  moduleNameMapper: {
    "@src/(.*)$": "<rootDir>/src/$1",
  },
  testPathIgnorePatterns: ["/node_modules/", "<rootDir>/build/"],
  globalTeardown: "<rootDir>/tests/teardown.ts",
};

Just a quick reminder for everyone (including my future self in about 6 months – Hi 👋 Yes, I’m talking to you!):

This can also occur when you’re trying to import a file that is importing a dependency that is simply not using the ES6 syntax. Most jest configurations are not (re-)compiling files from the node_modules directory, so make sure to import the CJS/UMD/ES6 version of your dependency, and not the ESM version. Sounds obvious and is definitely RTFM, but it took me a while to find this 🤷‍♂️

Have a similar issue

Hi everyone, I’m workin’ with a webpack.config.js'and main.js files, but I’m still getting errors, it must be the node version, I’ve the latest v14.4.0 and I’m still getting these errors.

I already did the type: module in package.json and it doesn’t work because I get another error in the terminal.

I always get these errors in all my projects, both with .ts and .js files, some time ago I didn’t get these errors, and I used to work with ES6 imports/exports, but recently, without knowing why, it doesn’t let me work anymore and I gotta import packages and modules with the CommonJS require().

screenshot 2020-06-16 a las 16 20 15

screenshot 2020-06-16 a las 16 20 23

screenshot 2020-06-16 a las 16 20 32

Facing same problem. .bablerc

{
  "presets": ["module:metro-react-native-babel-preset"]
}

package.json

{

  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest",
    "prepare": "patch-package",
    "postinstall": "jetify -r"
  },
  "rnpm": {
    "assets": [
      "./assets/fonts/"
    ]
  },
//this contains some other dependencies
  "dependencies": {
    "react": "^16.8.6",
    "react-native": "^0.59.2",
   "react-native-router-flux": "^4.0.6",
    "react-navigation": "^2.18.3",
  },
  "devDependencies": {
    "@babel/core": "^7.4.3",
    "babel-core": "^6.26.3",
    "babel-jest": "^23.4.2",
    "babel-preset-react-native": "^5.0.2",
    "jest": "^23.5.0",
    "jest-transform-stub": "^1.0.0",
    "jetifier": "^1.6.4",
    "metro-react-native-babel-preset": "^0.51.1",
    "react-test-renderer": "^16.3.1"
  },
  "jest": {
    "preset": "react-native",
    "transform": {
      "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
    },
    "transformIgnorePatterns": [
      "node_modules/(?!react-native|react-navigation)",
      "node_modules/(?!react-native|react-native-router-flux)",
    ],
    "moduleNameMapper": {
      ".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
    },
    "collectCoverage": true
  }
}

One of the test case which I am executing aboutus.test.js

import "react-native";
import AboutUs  from "../scenes/aboutus/aboutUs";
import renderer from "react-test-renderer";


const tree = renderer.create(<AboutUs />).toJSON();

it("renders Floating Input Screen ", () => {
  expect(tree).toMatchSnapshot();
});

On running npm test

_tests_/aboutus.test.js
   Test suite failed to run

 node_modules\react-navigation-deprecated-tab-navigator\src\index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import createTabNavigator from './createTabNavigator';
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
      at Object.<anonymous> (component/react-native-router-flux/src/navigationStore.js:20203:96)

Is there anything in my initial configuration, as it was working fine when i was using react native 0.53 version.

If you’re using Typescript, then you should install ts-jest and configure it!