Node.js Native ESM Support
Mocha supports writing your tests as ES modules, and not just using CommonJS. For example:
import { add } from "./add.mjs";import assert from "assert";
it("should add to numbers from an es module", () => { assert.equal(add(3, 5), 8);});To enable this you don’t need to do anything special.
Write your test file as an ES module.
In Node.js this means either ending the file with a .mjs extension, or, if you want to use the regular .js extension, by adding "type": "module" to your package.json.
More information can be found in the Node.js documentation.
Current Limitations
- Watch mode does not support ES Module test files
- Custom reporters and custom interfaces can only be CommonJS files
- Configuration file can only be a CommonJS file (
.mocharc.jsor.mocharc.cjs) - Mocha in Node.js version 24.4.0 or older silently ignored top level errors in ESM files.
If you cannot upgrade to a newer Node.js version, you can add
--no-experimental-require-moduleto theNODE_OPTIONSenvironment variable. - When using module-level mocks via libs like
proxyquire,rewiremockorrewire, hold off on using ES modules for your test files. You can switch to usingtestdouble, which does support ESM.