Skip to content

[Bug]: can't clear / reset / umock module affected by unstable_mockModule #13448

@koshic

Description

@koshic

Version

29.2.0

Steps to reproduce

Run this test in ESM mode:

test("can't reset ESM", async () => {
  // readFileSync shall fail due to wrong path
  const code = `
    import {readFileSync} from 'fs';
    console.log(readFileSync('totally fake path'));
  `;
  const module = `data:text/javascript,${encodeURIComponent(code)}`;

  // mock readFileSync
  jest.unstable_mockModule("fs", () => ({
    readFileSync: () => "fake",
  }));

  // works!
  await import(module);

  jest.clearAllMocks();
  jest.resetAllMocks();
  jest.restoreAllMocks();
  jest.resetModules();
  jest.unmock("fs");

  // shall fail, but still works
  await import(module);
});

Expected behavior

test failed at second import due to wrong path passed to readFileSync

Actual behavior

test passed

Additional context

unstable_mockModule uses _explicitShouldMockModule map (see line 1247)
https://github.com/facebook/jest/blob/faef42e391db8b0af456aa89ec1806751d40b42c/packages/jest-runtime/src/index.ts#L1230-L1249

unmock affects only _explicitShouldMock (CJS version of that map)
https://github.com/facebook/jest/blob/faef42e391db8b0af456aa89ec1806751d40b42c/packages/jest-runtime/src/index.ts#L1972-L1981

moreover, we have only 2 reference to '_explicitShouldMock.' - the first one is located in unstable_mockModule (we saw it before), and the second one is located in... teardown:
https://github.com/facebook/jest/blob/faef42e391db8b0af456aa89ec1806751d40b42c/packages/jest-runtime/src/index.ts#L1276

when I call '_explicitShouldMock.clear()' in my test (via monkey patching jest-runtime to provide access to internals), all work as expected - no more mocks instead of real modules.

Environment

System:
    OS: macOS 12.5.1
    CPU: (16) x64 Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
  Binaries:
    Node: 18.11.0 - ~/.nvm/versions/node/v18.11.0/bin/node
    Yarn: 4.0.0-rc.25 - ~/.nvm/versions/node/v18.11.0/bin/yarn
    npm: 8.19.2 - ~/.nvm/versions/node/v18.11.0/bin/npm

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions