menu

Questions & Answers

Jest Unexpected token 'export' when using d3

I have read many of the questions similar to mine, but none seem to fix my issue. I am using Vue3, TypeScript, Jest, and D3 v7. When I try to import * as d3 from "d3"; I get this error in my tests:

({"Object.<anonymous>":
  function(module,exports,require,__dirname,__filename,global,jest)
  {export * from "d3-array";

This error also occurs when I import d3 as such import { BaseType, Selection, Transition, select } from "d3";

I have tried updating my jest config's transformIgnorePatterns property to read but this doesn't work either:

transformIgnorePatterns: [
  "<rootDir>/node_modules/(?!d3-(array))",
]

Could someone explain to me the piece I am missing here? Also below is my entire jest.config.js file

module.exports = {
  collectCoverageFrom: [
    "**/src/**.ts", 
    "**/src/**/**.ts", 
    "!**/dist/**", 
    "!**/node_modules/**", 
    "!**/public/**"
  ],
  errorOnDeprecated: true,
  preset: "@vue/cli-plugin-unit-jest/presets/typescript",
  testMatch: ["**/*.spec.ts", "!**/node_modules/**"],
  testPathIgnorePatterns: ["<rootDir>/dist/", "<rootDir>/node_modules/"],
  "modulePaths": [
    "<rootDir>"
  ],
  transformIgnorePatterns: [
    "<rootDir>/node_modules/(?!d3-(array))",
  ],
  transform: {
    "^.+\\.ts": "ts-jest",
    "^.+\\.vue$": "vue-jest",
  },
};
Answers(2) :

A quick fix is to use the minified d3 build, which is already transpiled. Either import the minified build directly:

import * as d3 from 'd3/dist/d3.min'

demo 1

Or use a Jest config to map d3 to the minified build:

// jest.config.js
module.exports = {
  moduleNameMapper: {
    '^d3$': '<rootDir>/node_modules/d3/dist/d3.min.js',
  },
}

demo 2

If that's not an option, you can configure Jest to transpile d3 (and its dependencies that also require transpilation: internmap, delaunator, and robust-predicates):

// jest.config.js
module.exports = {
  transformIgnorePatterns: [
    '<rootDir>/node_modules/(?!d3|internmap|delaunator|robust-predicates)'
  ],
}

Note: The transpilation adds considerable time to the test run.

demo 3

Comments:
2023-01-23 23:20:11
For those using CRA: add this to package.json: "jest": { "moduleNameMapper": { "^d3$": "<rootDir>/node_modules/d3/dist/d3.min.js" }
2023-01-23 23:20:11
This worked great with Next.js using the SWC compiler (where configuring Jest to transpile the files with Babel isn't an option). Thanks!

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)"] },