jestjs / jest

Delightful JavaScript Testing.
https://jestjs.io
MIT License
44.31k stars 6.47k forks source link

[Bug]: Virtual mocks created with `jest.unstable_mockModule` do not work outside of the test file #15303

Open ygrandgirard opened 2 months ago

ygrandgirard commented 2 months ago

Version

29.7.0, also tested on 30.0.0-alpha.6

Steps to reproduce

  1. Clone https://github.com/ygrandgirard/jest-esm-mock-repro
  2. Run npm install
  3. Run npm test

Expected behavior

Both tests should pass.

Actual behavior

Additional context

The error apparently comes from here (perhaps this could cause issues too, I am not sure) because the mock is checked against this._virtualMocks instead of this._virtualModuleMocks. Checking against the correct map fixes my issue.

I could open a PR with one or both changes if you think it is that simple. To me, it looked like this part of the code is used with ESM mocks only, but I did not get too deep in it and I may be wrong.

Environment

System:
    OS: Windows 11 10.0.22631
    CPU: (16) x64 AMD Ryzen 7 5800H with Radeon Graphics
  Binaries:
    Node: 20.16.0 - C:\Program Files\nodejs\node.EXE
    npm: 10.8.1 - C:\Program Files\nodejs\npm.CMD
  npmPackages:
    jest: ^29.7.0 => 29.7.0
github-actions[bot] commented 1 month ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 30 days.

ygrandgirard commented 1 month ago

Up

My current way around this is to modify the jest module with patch-package in a npm postinstall script. It gets the job done but it is really annoying to have to do this extra work for mocking to work in ESM environments!

Below are the changes I needed to make it work. As I said before, if you think these are okay I can post a PR with them.

--- a/packages/jest-runtime/src/index.ts
+++ b/packages/jest-runtime/src/index.ts
@@ -1973,7 +1973,7 @@ class Runtime {
     const options: ResolveModuleConfig = {conditions: this.esmConditions};
     const moduleID = await this._resolver.getModuleIDAsync(
-      this._virtualMocks,
+      this._virtualModuleMocks,
       from,
       moduleName,
       options,
@@ -2019,7 +2019,7 @@ class Runtime {

     // transitive unmocking for package managers that store flat packages (npm3)
     const currentModuleID = await this._resolver.getModuleIDAsync(
-      this._virtualMocks,
+      this._virtualModuleMocks,
       from,
       undefined,
       options,

Edit: Oops, I just realized my diff contained the changes I ported from #15080 as well! That's now fixed.

github-actions[bot] commented 1 week ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 30 days.

ygrandgirard commented 1 week ago

Bump