Categories
TypeScript Answers

How to fix the ‘SyntaxError: Cannot use import statement outside a module’ with Jest and JavaScript?

Spread the love

To fix the ‘SyntaxError: Cannot use import statement outside a module’ with Jest, we need to tell Jest to transpile ES6 modules before we can use them.

To do this, we write

{
  //...
  "jest": {
    "preset": "react-native",
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native|react-(native|universal|navigation)-(.*)|@react-native-community/(.*)|@react-navigation/(.*)|bs-platform|(@[a-zA-Z]+/)?(bs|reason|rescript)-(.*)+)"
    ]
  }
  //...
}

in our Jest config.

We set transformIgnorePatterns to an array with the pattern of the module names that we want to transform before we run our tests.

Then Jest will transform the modules into something it can use.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *