{"slug": "jest-vitest-or-node-test-fixing-cannot-use-import-statement-outside-a-module-by", "title": "Jest, Vitest, or node:test? Fixing \"Cannot use import statement outside a module\" by Choosing the Right Runner", "summary": "A developer documented how the \"Cannot use import statement outside a module\" error in Jest stems from Jest running ESM and TypeScript test files through a default CommonJS transform, and laid out a decision table comparing Jest, Vitest, and node:test. The account recommends Vitest as the lowest-friction fix for new TypeScript/ESM projects, node:test for small projects with few mocks, and keeping Jest for large existing suites that already work, noting that Jest's native ESM path remains experimental and requires NODE_OPTIONS=--experimental-vm-modules.", "body_md": "If Jest just failed with `SyntaxError: Cannot use import statement outside a module`, your project is ESM and Jest is still running your files through a CommonJS pipeline. For a new TypeScript/ESM project, Vitest is the lowest-friction fix; `node:test` is enough if you have no browser code and few mocks; keep Jest if you have a large existing suite that already works. Below is why the error happens, the dead ends, and a decision table.\n\nThe full symptom usually looks like this:\n\n``` python\nSyntaxError: Cannot use import statement outside a module\n\n  1 | import { slugify } from \"./slugify.js\";\n    | ^^^^^^\n```\n\nJest runs each test file inside a sandboxed VM and, by default, expects CommonJS. Your source uses `import`, so something has to transform it to `require` before Jest executes it. If the transformer is missing, or it skips the file (commonly a dependency in `node_modules` that ships ESM only), you get this error.\n\nThe variations I see most often:\n\n`.ts` files are not transformed at all.`\"type\": \"module\"` in `package.json`, which makes Node treat `.js` files as ESM while Jest's default transform still assumes CJS.`node_modules`, which Jest ignores by default via `transformIgnorePatterns`.\nThe related error once you do go native ESM is `ReferenceError: jest is not defined`, because the `jest` global is not injected into ES modules; you must `import { jest } from \"@jest/globals\"`.\n\n**Takeaway: this error means \"the file was never compiled to something Jest's CommonJS runtime can run,\" not that your code is wrong.**\n\n`import.meta` are the usual casualties).`NODE_OPTIONS=--experimental-vm-modules` and is documented as experimental as of late 2026, and `jest.mock` does not hoist the same way under ESM (you need `jest.unstable_mockModule`).\nHere is what the native-ESM Jest route looks like, so you can judge the cost:\n\n```\nNODE_OPTIONS=--experimental-vm-modules npx jest\n// jest.config.js\nexport default {\n  transform: {}, // no CJS transform; Node loads ESM directly\n  extensionsToTreatAsEsm: [\".ts\"],\n};\n```\n\nIt runs, but you are opting into an experimental path and TypeScript still needs its own transform on top.\n\n**Takeaway: every Jest-side fix is a workaround for a runtime designed before ESM was the default.**\n\n|  | Jest | Vitest | node:test | \n|---|---|---|---|\n| ESM + TypeScript out of the box | No, needs transform config | Yes, via Vite's pipeline | ESM yes; TypeScript depends on your Node version (see below) | \n| Extra dependency | Yes (plus transformer) | Yes (plus Vite) | None, built into Node | \n| Jest-style API ( `describe` ,`expect` ,`vi.fn` ) | Native | Largely compatible | Different: `node:assert` ,`mock` from`node:test` | \n| Module mocking | Mature, hoisted `jest.mock` (CJS) | `vi.mock` , hoisted, works with ESM | Available, but more manual | \n| Watch mode, UI, browser tests | Watch yes | Watch, UI and browser mode | Watch via `--watch` , no UI | \n| Ecosystem (snapshots, matchers, tutorials) | Largest | Large, growing | Smallest | \n| Best fit | Big existing CJS/Babel suites | New TS/Vite/ESM projects | Libraries and small services with few mocks | \n\nAll three are real, maintained tools. The honest drawbacks:\n\n`expect`-style matchers, thinner mocking ergonomics, and the reporter and coverage story depends on your Node version. Check the Node docs for your version before relying on a flag.\n**Takeaway: the runner you pick should match your module system, not your muscle memory.**\n\nThis is the whole setup for a TypeScript ESM project that was failing under Jest:\n\n```\nnpm install -D vitest\n// src/slugify.ts\nexport function slugify(input: string): string {\n  return input\n    .toLowerCase()\n    .trim()\n    .replace(/[^a-z0-9]+/g, \"-\")\n    .replace(/^-+|-+$/g, \"\");\n}\njs\n// src/slugify.test.ts\nimport { describe, it, expect } from \"vitest\";\nimport { slugify } from \"./slugify\";\n\ndescribe(\"slugify\", () => {\n  it(\"collapses punctuation and trims dashes\", () => {\n    expect(slugify(\"  Hello, World!  \")).toBe(\"hello-world\");\n  });\n});\nnpx vitest run\n```\n\nNo transform config, no experimental flag. The one thing that tripped me up: if you want `describe`/` it`/` expect` as globals like Jest, set `test: { globals: true }` in `vitest.config.ts` and add `\"vitest/globals\"` to `types` in `tsconfig.json`; otherwise import them explicitly as above.\n\nIf you want the test runner that gets out of the way for a new TypeScript/ESM codebase, Vitest is the one that runs your existing `import` statements without a transform config.\n\n**Takeaway: Vitest removes this entire error class because it never asks you to compile ESM back to CommonJS.**\n\nFor a small library or CLI with plain functions, the built-in runner has zero install cost:\n\n``` python\n// slugify.test.mjs\nimport { test } from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { slugify } from \"./slugify.mjs\";\n\ntest(\"collapses punctuation\", () => {\n  assert.equal(slugify(\"  Hello, World!  \"), \"hello-world\");\n});\nnode --test\n```\n\nFor TypeScript, recent Node versions can run files containing only erasable type syntax (no enums or namespaces) without a separate compiler. As of late 2026 that is on by default in current releases, but it varies by version, so check `node --version` against the Node docs; otherwise pair it with `tsx`. If you reach for heavy module mocking, snapshots, or a DOM, you will start rebuilding what Vitest already has.\n\n**Takeaway: node:test is the right default for dependency-free libraries, and the wrong one once your tests need heavy mocking.**\n\n**Why does Jest say \"Cannot use import statement outside a module\"?**\n\nJest is executing a file that still contains ESM `import` syntax because no transformer converted it. Add a transform for the file type, switch to Jest's experimental native ESM mode, or use a runner that handles ESM natively like Vitest.\n\n**Is Vitest a drop-in replacement for Jest?**\n\nMostly, but not fully. The API is intentionally similar (`vi.fn` instead of `jest.fn`, `vi.mock` instead of `jest.mock`), yet timer, mocking and config details differ, so run your suite and expect to fix some tests.\n\n**Do I need Jest or Vitest if I use node:test?**\n\nNot for simple unit tests. You need them only when you want rich matchers, snapshots, a UI, or convenient module mocking.\n\nStarting a new TypeScript/ESM project: use Vitest. Maintaining a large CommonJS or Babel-based codebase where Jest already passes: leave it alone, and only add the ESM flag if a dependency forces you. Shipping a small dependency-free library or CLI: try `node:test` first and graduate to Vitest when mocking gets painful. Whichever you choose, pin it and check the docs against your Node version, since this area has been changing fast.", "url": "https://wpnews.pro/news/jest-vitest-or-node-test-fixing-cannot-use-import-statement-outside-a-module-by", "canonical_source": "https://dev.to/libme/jest-vitest-or-nodetest-fixing-cannot-use-import-statement-outside-a-module-by-choosing-the-213g", "published_at": "2026-11-22 22:04:24+00:00", "updated_at": "2026-11-22 22:11:35.496560+00:00", "lang": "en", "topics": ["developer-tools"], "entities": ["Jest", "Vitest", "Node.js", "Vite", "TypeScript"], "also_reported_by": [], "takeaway": "Match the test runner to your module system: Vitest handles ESM and TypeScript out of the box via Vite, while Jest's native ESM path needs NODE_OPTIONS=--experimental-vm-modules and jest.unstable_mockModule for mocking.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/jest-vitest-or-node-test-fixing-cannot-use-import-statement-outside-a-module-by", "markdown": "https://wpnews.pro/news/jest-vitest-or-node-test-fixing-cannot-use-import-statement-outside-a-module-by.md", "text": "https://wpnews.pro/news/jest-vitest-or-node-test-fixing-cannot-use-import-statement-outside-a-module-by.txt", "jsonld": "https://wpnews.pro/news/jest-vitest-or-node-test-fixing-cannot-use-import-statement-outside-a-module-by.jsonld"}}