ESM node test_error ai_generated true

TypeError: A dynamic import callback was not specified (Jest ESM)

ID: node/experimental-vm-modules

Also available as: JSON · Markdown
88%Fix Rate
90%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
20 active

Root Cause

Jest can't handle ES modules without --experimental-vm-modules flag.

generic

Workarounds

  1. 92% success Run Jest with experimental VM modules: NODE_OPTIONS=--experimental-vm-modules npx jest
    NODE_OPTIONS=--experimental-vm-modules npx jest

    Sources: https://jestjs.io/docs/ecmascript-modules

  2. 90% success Consider switching to Vitest which has native ESM support
    npm install -D vitest
    # vitest supports ESM natively

    Sources: https://vitest.dev/guide/

  3. 82% success Add transform config to jest.config.js for ESM files
    // jest.config.js:
    module.exports = {
      transform: { '^.+\\.m?js$': 'babel-jest' },
      transformIgnorePatterns: ['/node_modules/(?!esm-only-pkg)']
    };

    Sources: https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object

Dead Ends

Common approaches that don't work:

  1. Rewrite all tests to CommonJS 70% fail

    If your project is ESM, tests should be ESM too

  2. Use dynamic import() inside require-based tests 60% fail

    Awkward pattern that makes tests harder to read

Error Chain

Frequently confused with: