Skip to content

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

@joshkel

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

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