259

I'm using Jest to test my React app.

Recently, I added DeckGL to my app. My tests fail with this error:

Test suite failed to run

/my_project/node_modules/deck.gl/src/react/index.js:21
export {default as DeckGL} from './deckgl';
^^^^^^

SyntaxError: Unexpected token export

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:318:17)
  at Object.<anonymous> (node_modules/deck.gl/dist/react/deckgl.js:9:14)
  at Object.<anonymous> (node_modules/deck.gl/dist/react/index.js:7:15)

This looks like an issue with Jest transforming a node module before running it's tests.

Here is my .babelrc:

{
  "presets": ["react", "es2015", "stage-1"]
}

Here is my jest setup:

"jest": {
    "testURL": "http://localhost",
    "setupFiles": [
      "./test/jestsetup.js"
    ],
    "snapshotSerializers": [
      "<rootDir>/node_modules/enzyme-to-json/serializer"
    ],
    "moduleDirectories": [
      "node_modules",
      "/src"
    ],
    "moduleNameMapper": {
      "\\.(css|scss)$": "<rootDir>/test/EmptyModule.js"
    }
  },

I seem to have the correct things necessary to transform export {default as DeckGL }. So any ideas whats going wrong?

3
  • Did you forgot to add a semicolon to the line above the export? Commented Apr 4, 2018 at 9:00
  • @DonP, can you try using the recommended ts-jest and see if it helps? I don't want to crowd this question with another answer if it doesn't help you out Commented Apr 6, 2018 at 3:55
  • Nothing here helped but github.com/facebook/create-react-app/issues/… mentioned you can pass in transformIgnorePatterns as a command-line argument to npm/yarn/craco in package.json's scripts, and that worked! Commented Jun 23, 2022 at 20:58

21 Answers 21

219
+50

This means, that a file is not transformed through TypeScript compiler, e.g. because it is a JS file with TS syntax, or it is published to npm as uncompiled source files. Here's what you can do.

Adjust your transformIgnorePatterns allowed list:

{
  "jest": {
    "transformIgnorePatterns": [
      "node_modules/(?!@ngrx|(?!deck.gl)|ng-dynamic)"
    ]
  }
}

By default Jest doesn't transform node_modules, because they should be valid JavaScript files. However, it happens that library authors assume that you'll compile their sources. So you have to tell this to Jest explicitly. Above snippet means that @ngrx, deck and ng-dynamic will be transformed, even though they're node_modules.

Sign up to request clarification or add additional context in comments.

11 Comments

What is the reason for the nested negative lookahead (?!...(?!...)) in the regex?
where do I put this? which file?
@EladKatz I'm new to this, but I think this block is meant for package.json, and without the 'jest' wrapper you could put it in jest.config.js.
Might just want to simplify the RegExp like this: node_modules\/(?!(@ngrx|deck.gl|ng-dynamic))
@EladKatz in the jest.config.js file.
|
69

And if you are using 'create-react-app', it won't allow you to specify 'transformIgnorePatterns' via Jest property in package.json

As per this https://github.com/facebook/create-react-app/issues/2537#issuecomment-390341713

You can use CLI as below in your package.json to override and it works :

"scripts": {
  "test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!your-module-name)/\"",
},

3 Comments

CRA 3.0.2 added support for Jest transformIgnorePatterns in package.json.
Worth noting that if you're using react-app-rewired, it takes over the processing for the jest property in package.json, and concatenates rather than replaces. So this solution will not work and you will have to place it in the script options or inside the overrides script
My test configuration is created for "test": "jest --coverage --transformIgnorePatterns \"node_modules/(?!array-move)/\", when I run a particular test with the command npm run test test_filename.test.js it results in run all tests. Idk why this happened, maybe there are other people who have experienced the same case or can explain this case.
40

This is because Node.js cannot handle ES6 modules.

You should transform your modules to CommonJS therefore.

Babel 7 >=

Install npm install --save-dev @babel/plugin-transform-modules-commonjs

And to use only for test cases add to .babelrc, Jest automatically gives NODE_ENV=test global variable.

"env": {
    "test": {
      "plugins": ["@babel/plugin-transform-modules-commonjs"]
    }
}

Babel 6 >=

npm install --save-dev babel-plugin-transform-es2015-modules-commonjs

to .babelrc

"env": {
    "test": {
      "plugins": ["transform-es2015-modules-commonjs"]
    }
}

4 Comments

This works! However, make sure to run jest --clearCache I had to do that before it started working.
where do I add: "env": { "test": { "plugins": ["@babel/plugin-transform-modules-commonjs"] } }
@joeCarpenter to your .babelrc or to other babel config file you might be using eg babel.config.js. If you don't yet have one you can create new file in the project root with name .babelrc and add this under root { } -tags.
Had to combine this answer with @Ria Anggraini's answer to get things to work when running tests.
22

Jest by default won't compile files in the node_modules directory.

transformIgnorePatterns [array]

Default: ["/node_modules/"]

An array of regexp pattern strings that are matched against all source file paths before transformation. If the test path matches any of the patterns, it will not be transformed.Default: ["/node_modules/"]

DeckGL seems to be in ES6, to make jest able to read it, you need to compile this as well.
To do that, just add an exception for DeckGL in the transformignorePatterns

"transformIgnorePatterns": ["/node_modules/(?!deck\.gl)"]

https://facebook.github.io/jest/docs/en/configuration.html#transformignorepatterns-array-string

Comments

15

It was work around #1 on this page that fixed it for me though workaround #2 on that page is mentioned in above answers so they may also be valid.

"Specify the entry for the commonjs version of the corresponding package in the moduleNameMapper configuration"

jest.config.js

    moduleNameMapper: {
        "^uuid$": require.resolve("uuid"), 
        "^jsonpath-plus$": require.resolve("jsonpath-plus") 
...

Comments

12

In my case I use this config in the file package.json:

"jest": {
    "transformIgnorePatterns": [
      "!node_modules/"
    ]
  }

2 Comments

Does Jest really give special meaning to a preceding ! in transformIgnorePatterns? I'd guess this is effectively equivalent to writing transformIgnorePatterns: [].
Great answer. FYI if you want to exclude everything but your workspace you can write the pattern like this: "!node_modules/(?!@src/*.)"
7

I was having this issue with a monorepo. A package in the root node_modules was breaking my tests. I fixed by changing my local .babelrc file to babel.config.js. Explanation: https://github.com/facebook/jest/issues/6053#issuecomment-383632515

1 Comment

Thanks for pointing that out. It worked for me after renaming the file and adding the exception for my esm library in transformIgnorePatterns!
5
+50

I think Ria Anggraini's accepted solution above is correct, but it's worth noting if you're using Next.js that you might be affected by this issue. next/jest.js makes it hard to transpile modules in node_modules, but you can modify the baked config like this:

import nextJest from 'next/jest.js'
const createJestConfig = nextJest({
    dir: './',
})

// add any custom config to be passed to Jest
/** @type {import('jest').Config} */
const config = {
  ...
  // setting `transformIgnorePatterns` in here does not work
}

// work around https://github.com/vercel/next.js/issues/35634
async function hackJestConfig() {
    // createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
    const nextJestConfig = await createJestConfig(config)();
    // /node_modules/ is the first pattern, so overwrite it with the correct version
    nextJestConfig.transformIgnorePatterns[0] = '/node_modules/(?!(micromark-extension-gfm))/';
    return nextJestConfig;
}

export default hackJestConfig

1 Comment

Thanks a lot for this. Saved me a lot of time!
3

My solution to this issue with jest is to mock the esm files that it is having trouble with (in my case it is nanoid)

jest.config.js

{
  ...
  setupFiles: ["./mock.js"]
}

src/mock.js

jest.mock('nanoid', () => {
  return { nanoid: () => '1234' };
});

Comments

2

I had the exact same problem when using jest with vite+swc and a component using the d3 library (d3-array and d3-shape was having a problem).

This advice to add this to jest.config.js solved it:

transformIgnorePatterns: ['node_modules/(?!@ngrx|(?!deck.gl)|d3-scale)'],

This got me wondering why this worked because I don't use ngrx or deck.gl. But then I noticed that this is equivalent to:

 transformIgnorePatterns: ['(?!abc|(?!def))'],

The advice also works:

transformIgnorePatterns: ['!node_modules/'],

Which led me to the final answer of

transformIgnorePatterns: [],

Just adding this line with an empty array is the simplest answer which worked.

4 Comments

When you put: transformIgnorePatterns: [] That simply mean TypeScript will compile all of node_modules, which is a super slow operation if you've got a lot of node modules installed.
Well that is better than having an error and it not compiling at all. Clearly some issue with one of the dependencies, who knows, maybe they fixed it by now.
That's not how it works. The world is slowly moving from CommonJS to ES6 modules. That is why this problem exists.
@LodewijkBogaards Yes we are moving to ES6 modules. You seem to be commenting on something that is 8 months old. I can assure you that I was receiving the error "Jest gives an error: "SyntaxError: Unexpected token export"" and the above change worked to remove this error. Perhaps it was slower as you mention, but at least the tests worked. Now the world has moved on and we aren't using the same versions of the libraries anymore, and this isn't a problem anymore. Thank you for your interest.
1

I'm using a monorepo (it contains multiple packages for the frontend and backend).

The package I'm testing imports a file from another package that uses the dependency uuid.

All the files are in Typescript (not Javascript).

The package I'm testing has a tsconfig file for testing only, called tsconfig.test.json. It has the properties commonjs and allowJs. Adding allowJs solves the problem when importing uuid, I don't know why.

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "../../dist/out-tsc",
    "module": "commonjs",
    "types": [
      "jest",
      "node"
    ],
    // Necessary to import dependency uuid using CommonJS
    "allowJs": true
  },
  "include": [
    "jest.config.ts",
    "**/*.test.ts",
    "**/*.d.ts"
  ]
}

Comments

1

I was upgrading a project that uses a version of babel that reads the config from .babelrc, when I upgraded to a newer version I read:

https://babeljs.io/docs/en/configuration#whats-your-use-case

What's your use case?

You are using a monorepo?

You want to compile node_modules?

babel.config.json is for you!

On top of:

{
  "jest": {
    "transformIgnorePatterns": [
      "node_modules/(?!(module))"
    ]
  }
}

I renamed .babelrc to babel.config.json too.

Comments

1

I had the exact same problem when using jest 29.7.0 with React 18.

In my case this config worked after changing the .babelrc into babel.config.js

module.exports = {
  "jest": {
    "transformIgnorePatterns": [
      "node_modules/(?!(module))"
    ]
  }
}

Comments

0

This code worked for me // .babelrc

{
  "presets": [
    ["env", {
      "modules": "commonjs", // <- Check and see if you have this line
      "targets": {
        "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
      }
    }],
    "stage-2"
  ],
  "plugins": ["transform-vue-jsx", "transform-runtime"],
  "env": {
    "test": {
      "presets": ["env", "stage-2"],
      "plugins": ["transform-vue-jsx", "transform-es2015-modules-commonjs", "dynamic-import-node"]
    }
  }
}

jest understands commonJs so it needs babel to transform the code for it before use. Also jest uses caching when running code. So make sure you run jest --clearCache before running jest.

Tested Environment:
Node v8.13.0
Babel v6+
Jest v27

Comments

0

I got same error. Library A gave such error. I did not use this library in my code directly. I played with jest config a lot of time. But I found that I forget to mock library B in ...test.tsx file. After mocking there was not that error. Sounds pretty stupid but it works for me.

Comments

0

I had the same problem after upgrading 2 projects from Angular 12 to Angular 14 and 15.

After much searching, the ONLY thing that turned both projects in good ones again was by upgrading the 'Rxjs' package to a newer/newest version. The ONLY thing.

Be sure to have that RxJs upgraded. After that I made sure to have the tslib upgraded as well.

The base Jest configuration was via this course.

1 Comment

See which RXJS version is compatible with your version of Angular here: angular.dev/reference/versions#actively-supported-versions
0

Was having the same problem.

export function flatten (target, opts) {
^^^^^^

SyntaxError: Unexpected token 'export'

I made sure my jest was properly installed and set up, as per Next.js docs, but still same issue. None of the popular solutions here were working for me either.

However, while running npm i, I noticed this warning:

npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: '[email protected]',
npm WARN EBADENGINE   required: { node: '>=18' },
npm WARN EBADENGINE   current: { node: 'v16.19.1', npm: '8.19.3' }
npm WARN EBADENGINE }

Since version 6.0.0, the flat package is distributed in ECMAScript modules.

Solution

The quickest way to fix it was to downgrade it to a version that is compatible with my node.js and my project settings:

npm i flat@5

And since then I've been able to run jest as expected (perhaps updating the node.js version would've solved it too).

Comments

0

This works for me:

//jest.config.js

    const esModules = [
      'nanoid',
      'p-cancelable',
      'reaflow',
      'easy-email-core',
      'uuid/dist/esm-browser',
      'd3-path/src',
      'd3-shape/src',
    ].join('|');
    
    module.exports = {
      testEnvironment: 'jsdom',
      setupFiles: ['<rootDir>/setup.jest.js'],
      globals: {
        Uint8Array: Uint8Array,
      },
      transformIgnorePatterns: [`/node_modules/(?!${esModules})`],
      transform: {
        '^.+.[tj]sx?$': [
          'babel-jest',
        ],
      },
    };

In mi case all items within esModules were giving me errors of "SyntaxError: Unexpected token export"

then

//babel.config.js
module.exports = {
  // [...]
  presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript'],
  plugins: ['@babel/plugin-transform-react-jsx'],
  env: {
    test: {
      plugins: ['@babel/plugin-transform-modules-commonjs'],
    },
  },
};

Comments

0

In my case, it was due to a project exporting ESM syntax via .js and Jest interpreting that as CommonJS, despite following all the guides to overwrite transformIgnorePatterns.

The solution was to switch from jest to vitest.

Optionally you could a vitest.config.ts file and add a default config:

import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
  },
});

Because vitest does not export the Jest globals (like describe), you can either set globals: true, or manually import the required keywords in your test.

For a basic project, that's all that's needed. Vitest will handle ESM natively, and as an added bonus, it will be much faster.

Comments

-1

The bottom line here did it for me:

  transform: {
    '^.+\\.ts?$': ['ts-jest', { isolatedModules: true, useESM: true }],
    '^.+\\.tsx?$': [
      'ts-jest',
      { useESM: true, tsconfig: { jsx: 'react-jsx' } }
    ],
    '^.+\\.jsx?$': require.resolve('babel-jest')
  }

That is, in addition to my babel.config.js:

module.exports = {
  presets: [
    ['@babel/preset-env', { targets: { node: 'current' } }],
    '@babel/preset-typescript'
  ]
};

Hope this helps someone too! I've been using the plasmo framework for building browser extensions--nothing else helped me get Jest going.

Comments

-4

I had the same error of importing dataSet from vis-data.js library

import { DataSet } from 'vis-data/esnext';

So I just removed /esnext from the path and now it works:

import { DataSet } from 'vis-data';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.