CodewCaro.

Jest SyntaxError: Unexpected token 'export'

Caroline Cah
Caroline Cah

Have you configured jest together with react-testing-library and now gotten Jest SyntaxError: Unexpected token 'export' when building?


I tried multiple things, like modifying .babelrc and some dependencies, moduleNameMapper and transformIgnorePatterns in jest.config.js.


If you're seeing this error due to a third-party package that's using ES modules, you may need to tell Jest to transform that package. By default, Jest will not transform anything.


My solution to this was transformIgnorePatterns: ['/nodemodules/(?!@packageyouwanttoignore).+\\.js$', 'react-spring'],


In this way the jest configuration will not look in the specific package, for example jest tests on code that uses ES modules import/export without the correct configuration.


You could also test


Install Babel and Presets:


If you haven't already set up Babel for your project, you'll need to do that first. Babel will transpile your ES6+ code into code that Jest (and older versions of Node.js) can understand.


yarn add @babel/core @babel/preset-env @babel/preset-react

(@babel/preset-react is only needed if you're working with React.)


Babel Configuration:


Create a .babelrc or babel.config.js file at the root of your project (if you don't have one already).


For example, a .babelrc might look like:


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

This will ensure that your code is transpiled for the environment Jest runs in.


Jest Configuration:


If you don't have a Jest configuration set up, you might need one. This could be in your package.json under the jest key or in a separate jest.config.js file.


Make sure Jest is using Babel:


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

Install babel-jest:


Ensure babel-jest is installed:


yarn add babel-jest
More posts