-
-
Notifications
You must be signed in to change notification settings - Fork 31.7k
Test runner module mocking doesn't work for CJS if package exports are specified #58231
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Seems related #53634 |
The "module" field is nonstandard and node doesn't look at it, afaik. Does the same thing happen if you just delete the module field? |
@ljharb The example package should be installed into node_modules. // index.cjs
const add = (x, y) => x+y;
module.exports = {add} // index.js
export const add = (x, y) => x+y; {
"name": "example-package",
"type": "module",
"main": "index.js",
"exports": {
"default": {
"import": "./index.js",
"require": "./index.cjs"
}
},
"private": true
} // test.js
mock.module('example-package', {
namedExports: {
add(x, y) {
return 1+x+y;
}
},
});
describe('example-package', () => {
it('mocking problem in cjs', () => {
const {add} = require('example-package')
assert.strictEqual(add(4,5), 10); // fails
})
it('mocking works for esm', async () => {
const {add} = await import('example-package');
assert.strictEqual(add(4,5), 10);
})
}) Remove |
@ljharb this is a pretty common pattern across many npm libraries. It is also affecting https://github.com/remix-run/react-router v7 |
@JakobJingleheimer @cjihrig I would like to get your thoughts on this issue thx |
Hiya! Could you try setting |
My guess is that the test runner mocking utility uses the async loader hooks to mock CJS and uses a source text module facade for this, which ends up relying on the export detection using the static analysis that does not recognize patterns like EDIT: actually |
I'll be doing some work related to that in the next couple weeks, so if it is similar to that, I'll address it at the same time (it would happen to also fix this). |
Uh oh!
There was an error while loading. Please reload this page.
Version
22.15
Platform
Subsystem
node:mock
What steps will reproduce the bug?
The issue is for packages that expose esm
module
and cjsmain
. See Repo: https://github.com/sloops77/node-mock-bug for more examplesRather 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 exposesmodule
andmain
).How often does it reproduce? Is there a required condition?
defaultExport
.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
The text was updated successfully, but these errors were encountered: