Open
Description
Version
22.15
Platform
Darwin Andress-MacBook-Pro.local 24.4.0 Darwin Kernel Version 24.4.0: Fri Apr 11 18:33:47 PDT 2025; root:xnu-11417.101.15~117/RELEASE_ARM64_T6000 arm64
Subsystem
node:mock
What steps will reproduce the bug?
The issue is for packages that expose esm module
and cjs main
. See Repo: https://github.com/sloops77/node-mock-bug for more examples
Rather than create my own package the examples below use the nanoid
3.x package. The linked repo also shows that it is reproducible for the ethers package (which also exposes module
and main
).
// snippet of package.json from nanoid
{
"name": "nanoid",
"version": "3.3.11",
"description": "A tiny (116 bytes), secure URL-friendly unique string ID generator",
"type": "module",
"main": "index.cjs",
"module": "index.js",
...
// test.js
const {describe, it, mock} = require("node:test");
const assert = require("node:assert");
mock.module('nanoid', {
namedExports: {
nanoid() {
return '1234'
}
},
});
test('mocking problem in cjs', () => {
const {nanoid} = require('nanoid')
assert.strictEqual(nanoid(), '1234'); // fails test because cjs is not mocked
})
test('mocking works for esm', async () => {
const {nanoid} = await import('nanoid')
assert.strictEqual(nanoid(), '1234'); // works as it should
})
How often does it reproduce? Is there a required condition?
- For imported packages it seems 100% consistent. It also occurs for a module mock that uses
defaultExport
. - Node core modules do not reproduce this issue
What is the expected behavior? Why is that the expected behavior?
CJS & MJS files should receive a mocked module
What do you see instead?
CJS files receive the original module, not the mock. MJS files are fine as they receive the mock.
Additional information
No response