'How to set up Jest w/ESM to recognize non-cjs modules in node_modules

Have got a successful jest/esm setup, however occasionally a module is released that specifies both a main key (for commonjs) and a module key (for ESM) in its package.json. This leads to jest errors, for example with the uuid module:

/repo/path/node_modules/uuid/dist/esm-browser/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
                                                                                      ^^^^^^
SyntaxError: Unexpected token 'export'

I can see that dist/esm-browser/index.js is the file specified by the module key in package.json.

How can Jest w/ESM be configured to handle these cases, where stuff in node_modules is ESM?

Jest config:

{
    "resetMocks": true,
    "testEnvironment": "jsdom",
    "testMatch": [
      "**/src/**/*.(spec|test).[tj]s?(x)"
    ],
    "preset": "ts-jest/presets/default-esm",
    "extensionsToTreatAsEsm": [
      ".ts",
      ".tsx"
    ],
    "globals": {
      "ts-jest": {
        "useESM": true
      }
    },
    "globalSetup": "<rootDir>/jest/setup.cjs",
    "globalTeardown": "<rootDir>/jest/teardown.cjs",
    "watchPathIgnorePatterns": [
      "<rootDir>/.tmp"
    ],
    "moduleNameMapper": {
      "^~/(.*)$": "<rootDir>/src/$1",
      "^~components/(.*)$": "<rootDir>/src/components/$1",
      "^~util/(.*)$": "<rootDir>/src/util/$1",
      "^~types/(.*)$": "<rootDir>/src/types/$1"
    }
  }


Solution 1:[1]

I've had the same problem and it was fixed the same way as mentioned in this comment: https://github.com/nrwl/nx/issues/812#issuecomment-429420861 in my jest.config.js:

// list to add ESM to ignore
const esModules = ['uuid'].join('|');
// ...
module.exports = {
  //...
    transformIgnorePatterns: [`/node_modules/(?!${esModules})`],
  // ...
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jakub Havlik