Demo, all content is generated
Question

Jest: 'SyntaxError: Cannot use import statement outside a module' after Claude changed the project to ESM

Solved · 981 views · asked by theo_side · edited

Small Node API. Claude Code added "type": "module" to package.json to fix an import from a new package. The app runs. All my Jest tests now fail with:

SyntaxError: Cannot use import statement outside a module

Claude has tried 4 different jest.config setups (babel-jest, ts-jest presets, transformIgnorePatterns), each fails differently. I'm going in circles.

What I’ve tried

All four configs Claude suggested, removing type: module (then the app breaks), running with --experimental-vm-modules (different error).

Comment
How many tests, roughly? And is it TypeScript? katja_s · edited
About 30, yes TS. theo_side · edited

2 answers

Marked as helpful by the asker
katja_s · edited

Jest's ESM support still requires experimental flags and is fiddly with TypeScript. For a small project the fastest way out of the loop is to switch to Vitest, which is ESM-native and has a nearly identical API:

npm rm jest ts-jest babel-jest @types/jest
npm i -D vitest
"scripts": { "test": "vitest run" }

In the tests: jest.fn()vi.fn(), jest.mockvi.mock, add import { describe, it, expect, vi } from "vitest" (or set globals: true). Everything else (describe, expect, matchers) mostly works as is.

Took me 20 minutes for a 60-test project.

Comment
Welcome to Vitest. katja_s · edited
Did it with Claude with exactly this list. 31 tests green, 2 needed vi.mock changes. Deleted jest.config.js, felt great. theo_side · edited
Vitest runs on Node just fine too, people think it's frontend-only. marco_py · edited
marco_py · edited

If you must stay on Jest: often the error comes from a dependency in node_modules that ships ESM only, not from your own files. Look at the stack trace. If it points into node_modules/some-pkg, Jest isn't transforming that package, and the fix is transformIgnorePatterns: ["node_modules/(?!some-pkg)"] plus a transformer. But yes, Vitest is less pain.

Comment