3

I'm trying to understand how to fix the following error using Jest in my unit tests in NodeJS.

The test run with this command "test": "NODE_ENV=test jest spec/* -i --coverage --passWithNoTests",

Jest error

I'm also using babel and this is my config

{
  "presets": [["@babel/env", { "targets": { "node": "current" } }]],
  "plugins": [
    "@babel/plugin-syntax-dynamic-import",
    ["babel-plugin-inline-import", { "extensions": [".gql"] }],
    ["@babel/plugin-proposal-decorators", { "legacy": true }]
  ]
}

In package.json I have this

"jest": {
    "verbose": true,
    "collectCoverageFrom": [
      "spec/**/*.js"
    ]
  },

I tried several guides online but cannot find a solution to this

Jakub
  • 2,367
  • 6
  • 31
  • 82

2 Answers2

0

You've got Jest successfully configured to transform your code, but it is not transforming modules that you're importing—in this case node-fetch, which has the import keyword in its source code (as seen in your error). This is because, by default, Jest is configured not to transform files in node_modules:

transformIgnorePatterns [array]

Default: ["/node_modules/", "\.pnp\.[^\/]+$"]

An array of regexp pattern strings that are matched against all source file paths before transformation. If the file path matches any of the patterns, it will not be transformed.

You can set transformIgnorePatterns to exclude certain packages in node_modules with a jest.config.js like this:

const esModules = [
  'node-fetch',
  'data-uri-to-buffer',
  'fetch-blob',
  'formdata-polyfill',
].join('|');

module.exports = {
  transformIgnorePatterns: [
    `/node_modules/(?!${esModules})`,
    '\\.pnp\\.[^\\/]+$',
  ],
};

(see https://github.com/nrwl/nx/issues/812#issuecomment-429420861)

Dmitry Minkovsky
  • 36,185
  • 26
  • 116
  • 160
-1

If you have .babelrc try to rename it to babel.config.js

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

but also this (there's more in the discussion) Jest won't transform the module - SyntaxError: Cannot use import statement outside a module