Skip to content

Node.js Native ESM Support

Mocha supports writing your tests as ES modules, and not just using CommonJS. For example:

test.mjs
import { add } from "./add.mjs";
import assert from "node: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.

  • Watch mode does not support ES Module test files
  • Custom reporters and custom interfaces can only be CommonJS files
  • 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-module to the NODE_OPTIONS environment variable.
  • When using module-level mocks via libs like proxyquire, rewiremock or rewire, hold off on using ES modules for your test files. You can switch to using testdouble, which does support ESM.
Morty Proxy This is a proxified and sanitized view of the page, visit original site.