[Bug]: jest.spyOn() does not work on ESM outside of the test scope
Author: electriquoCreated Jul 23, 2025Updated Sep 9, 2026
LabelsNeeds TriageBug Report
Version
30.0.4
Steps to reproduce
- Clone https://github.com/electriquo/jest-spyon-err
- Follow the README
- Executing
npm run testoutputsin bar: originalwhere it should bein bar: mocked
Expected behavior
The mocked value in the test should persist both inside and outside the test, meaning that the mocked property should be effective wherever it's used. Specifically, in bar: mocked should print to standard output when running npm run test
Actual behavior
Executing npm run test outputs in bar: original where it should be in bar: mocked
Additional context
I understand that jest.unstable_mockModule() is the recommended method for mocking ESM modules, but my goal is to mock a specific function rather than the entire module. Therefore, I am using jest.spyOn() to mock the behavior of an ESM function.
In particular, I want to mock the return value of the foo() function so that it returns a value different from its original behavior.
Environment
System:
OS: macOS 15.5
CPU: (10) arm64 Apple M2 Pro
Binaries:
Node: 22.17.1 - ~/.nvm/versions/node/v22.17.1/bin/node
Yarn: 1.22.22 - ~/.nvm/versions/node/v22.17.1/bin/yarn
npm: 11.4.2 - ~/.nvm/versions/node/v22.17.1/bin/npm
pnpm: 10.13.1 - ~/.nvm/versions/node/v22.17.1/bin/pnpm
npmPackages:
jest: 30.0.5 => 30.0.5
Source: jestjs/jest