Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest tests failing on d3 import

I'm running the test

import { render } from '@testing-library/react';
import MyComponent from '../../../../components/MyComponent';

test('renders MyComponent', () => {
  render(<MyComponent />);
});

on a React app component using d3 with imports as follows:

import React from 'react';
import * as d3 from 'd3';

using the command

react-scripts test

This yields an error on the d3 import:

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

/Users/wogsland/Projects/sepia/node_modules/d3/src/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from "d3-array";
                                                                                         ^^^^^^

SyntaxError: Unexpected token 'export'

What am I missing? The component works fine in the browser, it just fails on the most basic of tests.

like image 543
wogsland Avatar asked Sep 06 '21 13:09

wogsland


2 Answers

Following the tip from Tiep Phan's answer I added the following to my package.json file:

"jest": {
    "transformIgnorePatterns": ["/node_modules/(?!d3|d3-array|internmap|delaunator|robust-predicates)"]
},
like image 79
wogsland Avatar answered Nov 15 '22 05:11

wogsland


To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.

From the above suggestions, we can tell Jest not to parse ES modules in node_modules.

In your jest.config.js file, you can add the following lines. You can add any ES module you want to the array.

const esModules = ['d3', 'd3-array', 'other-d3-module-if-needed'].join('|');

module.exports = {
  // ...
  transformIgnorePatterns: [`/node_modules/(?!${esModules})`],
  // ...
};
like image 29
Tiep Phan Avatar answered Nov 15 '22 05:11

Tiep Phan