Don't rely on inline requires to apply mocks in JS tests #59307

Closed
robhogan opened 1:16pm on October 21, 2026 wanted to merge 50 Ξ” into facebook/react-native main from
robhogan/jest-mocks-without-inline-requires
Diff Delta:
50
About 15 Diff Delta/hour
Classified as:  General

robhogan's Description of Work

Summary:

Test only change. RN's own Jest transform (jest/preprocessor.js, for this repo's own tests, not public) doesn't include babel-plugin-jest-hoist, so jest.mock calls run where they're written. Several tests only saw their mocks because inline requires deferred the require of the module under test (or of its dependencies) until first use.

That only works for destructured requires like const {foo} = require('./foo') while the Babel preset lowers destructuring, which in this config it currently does only as a side effect of lowering generators with regenerator. https://github.com/react/react-native/pull/59303 removes that, and 114 tests across these 16 suites fail.

This makes the tests install their mocks before the modules under test load, so they pass either way, without diverging Jest's transform from the app's:


  • Require modules under test after the jest.mock calls that affect them.

  • Use mock factories instead of spies or automocks where the code under test binds a function when it loads, or loads an ESM-only package (@octokit/rest).

  • Re-require modules after jest.resetModules() where tests reset the registry (publish-npm, Animated).

The release script tests in particular are dangerous when their mocks silently stop applying - locally, they ran the real version bump against the checkout.

Changelog:

[INTERNAL] [CHANGED] - Don't rely on inline requires to apply mocks in JS tests

Test Plan:

The full Jest suite passes on this PR (6,284 tests), and with https://github.com/react/react-native/pull/59303 applied on top (6,285), both under Node 24 with --no-cache. Without this PR, #59303 fails 114 tests in 16 suites, matching its CI.

16 total changed files
Loading changes...
Loading changes...
Loading changes...
Loading changes...
Loading changes...
Loading changes...
Loading changes...
Loading changes...
Loading changes...
Loading changes...
Loading changes...
Loading changes...
Loading changes...
Loading changes...
Loading changes...
Loading changes...
End of PR:
LGTM-land is officially in view