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

Sometimes, we want to fix the ‘SyntaxError: Cannot use import statement outside a module’ with Jest

In this article, we’ll look at how to fix the ‘SyntaxError: Cannot use import statement outside a module’ with Jest.

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

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.

Conclusion

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.