Skip to content

[Bug]: Importing from @jest/globals elsewhere breaks unstable_mockModule #15772

Closed

Description

@joshkel

Version

30.0.5

Steps to reproduce

  1. Clone from https://github.com/joshkel/jest-globals-bug
  2. npm i
  3. npm run tets

Expected behavior

Mocking ../makeId.js from src/unit/__tests__/makeId.test.js works, because src/unit/makeId.ts exists.

Actual behavior

Error message:

 FAIL  src/unit/__tests__/makeId.test.js
  ● Test suite failed to run

    Cannot find module '../makeId.js' from 'src/setupTests.js'

      2 | import { makeId } from '../makeId.js';
      3 |
    > 4 | jest.unstable_mockModule('../makeId.js', () => ({
        |      ^
      5 |     makeId: jest.fn(() => 'aaaa'),
      6 | }));
      7 |

      at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/index.js:863:11)
      at unstable_mockModule (src/unit/__tests__/makeId.test.js:4:6)

Additional context

This problem is caused if the @jest/globals module is referenced elsewhere (for example, in a setupTestsAfterEnv file) before it's imported in a test file. The first time @jest/globals is imported, it's synthesized with the path of that file that imported it and cached. All subsequent imports are then bound to the path of whatever first imported it and use that for path resolution, instead of properly resolving paths as relative to their own locations.

Environment

System:
    OS: macOS 15.5
    CPU: (10) arm64 Apple M1 Pro
  Binaries:
    Node: 22.17.1 - ~/.nvm/versions/node/v22.17.1/bin/node
    Yarn: 1.22.22 - /opt/homebrew/bin/yarn
    npm: 10.9.2 - ~/.nvm/versions/node/v22.17.1/bin/npm
    pnpm: 10.13.1 - ~/.nvm/versions/node/v22.17.1/bin/pnpm
    bun: 1.2.19 - /opt/homebrew/bin/bun
  npmPackages:
    jest: ^30 => 30.0.5

Activity

  1. added 2 commits that reference this issue on Aug 4, 2025
    3a1f400
    a46b5c0
  2. collinmurd commented on Aug 6, 2025

    @collinmurd

    I found a workaround to be adding jest.resetModules() to the end of your setupTestsAfterEnv file (or wherever that first reference is).

  3. github-actions commented on Sep 27, 2025

    @github-actions

    This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
    Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

  4. locked as resolved and limited conversation to collaborators on Sep 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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