Skip to content
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

Feature Request: Module level mocking #51164

Open
jasonwilliams opened this issue Dec 15, 2023 · 2 comments
Open

Feature Request: Module level mocking #51164

jasonwilliams opened this issue Dec 15, 2023 · 2 comments
Labels
feature request Issues that request new features to be added to Node.js.

Comments

@jasonwilliams
Copy link

What is the problem this feature will solve?

Currently you can't mock external or built-in modules which makes it difficult if you code imports a module that may run some side-effects and you have no control over it.

There may be some built in modules which you need to stub out but don't have access to during a test run.

What is the feature you are proposing to solve the problem?

Allowing us to use the built-in test runner to mock modules entirely.

There has already been some work in this by @cjihrig

I think the biggest things missing before I can open a PR are related to ESM loaders and are tracked in #49472 and #49473.

Both of those issues look to be resolved now, I don't know what the current blockers are for this

What alternatives have you considered?

No response

@jasonwilliams jasonwilliams added the feature request Issues that request new features to be added to Node.js. label Dec 15, 2023
@jrson83
Copy link

jrson83 commented Dec 16, 2023

When I was searching for a workaround, how to mock imports with the native test runner I found this looking very similar:

https://github.com/nodejs/node/blob/main/test/es-module/test-esm-loader-mock.mjs

I can't tell if this is already integrated, just missing the new types in @types/node?

@aduh95
Copy link
Contributor

aduh95 commented Dec 24, 2023

It's already possible to mock things as the test linked below using the experimental Customization Hook API (https://nodejs.org/api/module.html#customization-hooks). Note that it should work only on Node.js 18.19+/20.6+.

Here are the files to set it up, and as you can see, it's only using public APIs:

https://github.com/nodejs/node/blob/6a5394ea7dc62b044ed826a7c8d18506ab532b96/test/fixtures/es-module-loaders/mock.mjs
https://github.com/nodejs/node/blob/6a5394ea7dc62b044ed826a7c8d18506ab532b96/test/fixtures/es-module-loaders/mock-loader.mjs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request Issues that request new features to be added to Node.js.
Projects
Status: Pending Triage
Development

No branches or pull requests

3 participants