Fix “Cannot use import statement outside a module” in Jest



 🧨 The Error


You're using ES modules (import/export) in your code or test files, and you run:

npm test

Only to see this:

SyntaxError: Cannot use import statement outside a module


✅ Why it Happens


Jest runs on Node.js, and by default, it expects CommonJS (require/module.exports) syntax.


If you're using import in your test or source files, Jest needs to know:


  • You're using ES Modules (ESM)
  • How to load and execute ESM correctly, especially in sandboxed environments

🛠 The Quick Fix (No Babel Needed)


1️⃣ Tell Node your project uses ES modules


In your package.json:

{
  "type": "module",
  "scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
  }
}

"type": "module" enables import/export
--experimental-vm-modules tells Node to allow ESM in Jest's sandbox

2️⃣ Create jest.config.js using ESM

// jest.config.js
export default { testEnvironment: 'node', // or 'jsdom' if you're testing DOM };

export default is needed because you're in ESM mode now
module.exports = {} will fail here


🔍 Bonus: Why --experimental-vm-modules?

Jest uses Node's vm module internally to run your tests in isolated environments.

But vm doesn’t fully support import/export without this flag.

--experimental-vm-modules unlocks that ESM support, allowing Jest to handle import syntax cleanly. 


🧪 Alternative: Babel (if you want to go that route)

If you don’t want the --experimental flag in production setups, you can:

  • Use Babel to transpile ES modules to CommonJS

  • Tell Jest to load the transpiled version

But that adds build tooling complexity. For most projects, the solution above is simpler and more native.



✅ Final Project Checklist

  • "type": "module" in package.json

  • ✅ Custom test command using --experimental-vm-modules

  • ✅ ESM-friendly jest.config.js

  • ✅ All code uses import/export

No comments:

Theme images by merrymoonmary. Powered by Blogger.