mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
Don't rely on inline requires to apply mocks in JS tests (#59307)
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
Pull Request resolved: https://github.com/react/react-native/pull/59307
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, https://github.com/react/react-native/issues/59303 fails 114 tests in 16 suites, matching its CI.
Reviewed By: christophpurrer
Differential Revision: D126757286
Pulled By: javache
fbshipit-source-id: ce39217579aa9805f74786ee9b669bf411e97191
This commit is contained in:
1 parent
5b6f18b036
commit
a96b0e424c
16 files changed
+121
-84
No files matched your search
@@ -7,11 +7,6 @@
|
||||
* @format
|
||||
*/
|
||||
|
||||
const {
|
||||
publishTemplate,
|
||||
verifyPublishedTemplate,
|
||||
} = require('../publishTemplate');
|
||||
|
||||
const mockRun = jest.fn();
|
||||
const mockSleep = jest.fn();
|
||||
const mockGetNpmPackageInfo = jest.fn();
|
||||
@@ -29,6 +24,11 @@ jest.mock('../verifyPublishedPackage.js', () => ({
|
||||
verifyPublishedPackage: mockVerifyPublishedPackage,
|
||||
}));
|
||||
|
||||
const {
|
||||
publishTemplate,
|
||||
verifyPublishedTemplate,
|
||||
} = require('../publishTemplate');
|
||||
|
||||
const getMockGithub = () => ({
|
||||
rest: {
|
||||
actions: {
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
* @format
|
||||
*/
|
||||
|
||||
const {verifyArtifactsAreOnMaven} = require('../verifyArtifactsAreOnMaven');
|
||||
|
||||
const mockSleep = jest.fn();
|
||||
const silence = () => {};
|
||||
const mockFetch = jest.fn();
|
||||
@@ -19,6 +17,8 @@ jest.mock('../utils.js', () => ({
|
||||
sleep: mockSleep,
|
||||
}));
|
||||
|
||||
const {verifyArtifactsAreOnMaven} = require('../verifyArtifactsAreOnMaven');
|
||||
|
||||
process.exit = mockExit;
|
||||
global.fetch = mockFetch;
|
||||
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
* @format
|
||||
*/
|
||||
|
||||
const {verifyPublishedPackage} = require('../verifyPublishedPackage');
|
||||
|
||||
const mockRun = jest.fn();
|
||||
const mockSleep = jest.fn();
|
||||
const mockGetNpmPackageInfo = jest.fn();
|
||||
@@ -23,6 +21,8 @@ jest.mock('../utils.js', () => ({
|
||||
getNpmPackageInfo: mockGetNpmPackageInfo,
|
||||
}));
|
||||
|
||||
const {verifyPublishedPackage} = require('../verifyPublishedPackage');
|
||||
|
||||
describe('#verifyPublishedPackage', () => {
|
||||
beforeEach(jest.clearAllMocks);
|
||||
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
* @format
|
||||
*/
|
||||
|
||||
const {verifyReleaseOnNpm} = require('../verifyReleaseOnNpm');
|
||||
|
||||
const mockVerifyPublishedPackage = jest.fn();
|
||||
const silence = () => {};
|
||||
|
||||
@@ -21,6 +19,8 @@ jest.mock('../verifyPublishedPackage.js', () => ({
|
||||
verifyPublishedPackage: mockVerifyPublishedPackage,
|
||||
}));
|
||||
|
||||
const {verifyReleaseOnNpm} = require('../verifyReleaseOnNpm');
|
||||
|
||||
describe('#verifyReleaseOnNPM', () => {
|
||||
beforeEach(jest.clearAllMocks);
|
||||
|
||||
|
||||
+28
-21
@@ -10,27 +10,15 @@
|
||||
|
||||
'use-strict';
|
||||
|
||||
import type {ParserType} from '../errors';
|
||||
// The buildSchema tests spy on `getConfigType`, which parsers-commons reads when
|
||||
// it loads, so it's wrapped before any module that uses it is required.
|
||||
jest.mock('../utils', () => {
|
||||
const actual = jest.requireActual<Utils>('../utils');
|
||||
return {...actual, getConfigType: jest.fn(actual.getConfigType)};
|
||||
});
|
||||
|
||||
import {FlowParser} from '../flow/parser';
|
||||
import {MockedParser} from '../parserMock';
|
||||
import {
|
||||
assertGenericTypeAnnotationHasExactlyOneTypeParameter,
|
||||
buildSchema,
|
||||
buildSchemaFromConfigType,
|
||||
createComponentConfig,
|
||||
getCommandOptions,
|
||||
getCommandTypeNameAndOptionsExpression,
|
||||
getOptions,
|
||||
getTypeResolutionStatus,
|
||||
handleGenericTypeAnnotation,
|
||||
isObjectProperty,
|
||||
parseModuleName,
|
||||
parseObjectProperty,
|
||||
propertyNames,
|
||||
unwrapNullable,
|
||||
wrapNullable,
|
||||
} from '../parsers-commons';
|
||||
import type {ParserType} from '../errors';
|
||||
import typeof * as Utils from '../utils';
|
||||
|
||||
const {
|
||||
IncorrectModuleRegistryCallArgumentTypeParserError,
|
||||
@@ -46,6 +34,25 @@ const {
|
||||
} = require('../errors');
|
||||
const {buildComponentSchema} = require('../flow/components');
|
||||
const {flowTranslateTypeAnnotation} = require('../flow/modules/index');
|
||||
const {FlowParser} = require('../flow/parser');
|
||||
const {MockedParser} = require('../parserMock');
|
||||
const {
|
||||
assertGenericTypeAnnotationHasExactlyOneTypeParameter,
|
||||
buildSchema,
|
||||
buildSchemaFromConfigType,
|
||||
createComponentConfig,
|
||||
getCommandOptions,
|
||||
getCommandTypeNameAndOptionsExpression,
|
||||
getOptions,
|
||||
getTypeResolutionStatus,
|
||||
handleGenericTypeAnnotation,
|
||||
isObjectProperty,
|
||||
parseModuleName,
|
||||
parseObjectProperty,
|
||||
propertyNames,
|
||||
unwrapNullable,
|
||||
wrapNullable,
|
||||
} = require('../parsers-commons');
|
||||
const {buildModuleSchema} = require('../parsers-commons.js');
|
||||
const {Visitor} = require('../parsers-primitives');
|
||||
const {wrapComponentSchema} = require('../schema.js');
|
||||
@@ -665,7 +672,7 @@ describe('buildSchemaFromConfigType', () => {
|
||||
});
|
||||
|
||||
describe('buildSchema', () => {
|
||||
const getConfigTypeSpy = jest.spyOn(require('../utils'), 'getConfigType');
|
||||
const getConfigTypeSpy = require('../utils').getConfigType;
|
||||
|
||||
describe('when there is no codegenNativeComponent and no TurboModule', () => {
|
||||
const contents = '';
|
||||
|
||||
@@ -12,13 +12,13 @@ import * as React from 'react';
|
||||
|
||||
const {PlatformColor} = require('../../StyleSheet/PlatformColorValueTypes');
|
||||
let Animated = require('../Animated').default;
|
||||
const AnimatedProps = require('../nodes/AnimatedProps').default;
|
||||
const {
|
||||
let AnimatedProps = require('../nodes/AnimatedProps').default;
|
||||
let {
|
||||
create,
|
||||
unmount,
|
||||
update,
|
||||
} = require('@react-native/jest-preset/jest/renderer');
|
||||
const TestRenderer = require('react-test-renderer');
|
||||
let TestRenderer = require('react-test-renderer');
|
||||
|
||||
// WORKAROUND: `jest.runAllTicks` skips tasks scheduled w/ `queueMicrotask`.
|
||||
function mockQueueMicrotask() {
|
||||
@@ -37,6 +37,16 @@ function mockQueueMicrotask() {
|
||||
describe('Animated', () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
// Reload after the reset, so that Animated and the renderer share a copy
|
||||
// of React.
|
||||
Animated = require('../Animated').default;
|
||||
AnimatedProps = require('../nodes/AnimatedProps').default;
|
||||
({
|
||||
create,
|
||||
unmount,
|
||||
update,
|
||||
} = require('@react-native/jest-preset/jest/renderer'));
|
||||
TestRenderer = require('react-test-renderer');
|
||||
});
|
||||
|
||||
mockQueueMicrotask();
|
||||
|
||||
+9
-9
@@ -10,15 +10,6 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
const BackHandler: $FlowFixMe = require('../../Utilities/BackHandler').default;
|
||||
const LogBoxData = require('../Data/LogBoxData');
|
||||
const LogBoxLog = require('../Data/LogBoxLog').default;
|
||||
const {
|
||||
_LogBoxInspectorContainer: LogBoxInspectorContainer,
|
||||
} = require('../LogBoxInspectorContainer');
|
||||
const render = require('@react-native/jest-preset/jest/renderer');
|
||||
const React = require('react');
|
||||
|
||||
// Mock `LogBoxInspector` because we are interested in snapshotting the behavior
|
||||
// of `LogBoxInspectorContainer`, not `LogBoxInspector`.
|
||||
jest.mock('../UI/LogBoxInspector', () => ({
|
||||
@@ -30,6 +21,15 @@ jest.mock('../../Utilities/BackHandler', () =>
|
||||
require('../../Utilities/__mocks__/BackHandler'),
|
||||
);
|
||||
|
||||
const BackHandler: $FlowFixMe = require('../../Utilities/BackHandler').default;
|
||||
const LogBoxData = require('../Data/LogBoxData');
|
||||
const LogBoxLog = require('../Data/LogBoxLog').default;
|
||||
const {
|
||||
_LogBoxInspectorContainer: LogBoxInspectorContainer,
|
||||
} = require('../LogBoxInspectorContainer');
|
||||
const render = require('@react-native/jest-preset/jest/renderer');
|
||||
const React = require('react');
|
||||
|
||||
describe('LogBoxInspectorContainer', () => {
|
||||
let output;
|
||||
|
||||
|
||||
+7
-7
@@ -10,13 +10,6 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
const BackHandler: $FlowFixMe = require('../../Utilities/BackHandler').default;
|
||||
const LogBoxData = require('../Data/LogBoxData');
|
||||
const LogBoxLog = require('../Data/LogBoxLog').default;
|
||||
const {LogBoxNotificationContainer} = require('../LogBoxNotificationContainer');
|
||||
const render = require('@react-native/jest-preset/jest/renderer');
|
||||
const React = require('react');
|
||||
|
||||
// Mock `LogBoxLogNotification` because we are interested in snapshotting the
|
||||
// behavior of `LogBoxNotificationContainer`, not `LogBoxLogNotification`.
|
||||
jest.mock('../UI/LogBoxNotification', () => ({
|
||||
@@ -28,6 +21,13 @@ jest.mock('../../Utilities/BackHandler', () =>
|
||||
require('../../Utilities/__mocks__/BackHandler'),
|
||||
);
|
||||
|
||||
const BackHandler: $FlowFixMe = require('../../Utilities/BackHandler').default;
|
||||
const LogBoxData = require('../Data/LogBoxData');
|
||||
const LogBoxLog = require('../Data/LogBoxLog').default;
|
||||
const {LogBoxNotificationContainer} = require('../LogBoxNotificationContainer');
|
||||
const render = require('@react-native/jest-preset/jest/renderer');
|
||||
const React = require('react');
|
||||
|
||||
describe('LogBoxNotificationContainer', () => {
|
||||
let output;
|
||||
|
||||
|
||||
+11
-4
@@ -10,11 +10,18 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
// headers-xcframework reads `execFileSync` when it loads, so it's mocked before
|
||||
// the module is required.
|
||||
const mockExecFileSync = jest.fn();
|
||||
jest.mock('node:child_process', () => ({
|
||||
...jest.requireActual('node:child_process'),
|
||||
execFileSync: mockExecFileSync,
|
||||
}));
|
||||
|
||||
const {
|
||||
buildDepsHeadersXcframework,
|
||||
stubSlicesFromXcframework,
|
||||
} = require('../headers-xcframework');
|
||||
const childProcess = require('node:child_process');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
@@ -67,9 +74,9 @@ describe('stubSlicesFromXcframework', () => {
|
||||
// SupportedPlatform/Variant -> key mapping and the unknown-slice guard can be
|
||||
// tested without a real xcframework or macOS tooling.
|
||||
const mockPlist = (obj /*: unknown */) =>
|
||||
jest
|
||||
.spyOn(childProcess, 'execFileSync')
|
||||
.mockReturnValue(Buffer.from(JSON.stringify(obj) ?? '', 'utf8'));
|
||||
mockExecFileSync.mockReturnValue(
|
||||
Buffer.from(JSON.stringify(obj) ?? '', 'utf8'),
|
||||
);
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
|
||||
@@ -10,6 +10,12 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
// Mock all required modules
|
||||
jest.mock('../utils');
|
||||
jest.mock('../headers-mappings');
|
||||
jest.mock('node:fs');
|
||||
jest.mock('node:path');
|
||||
|
||||
const {
|
||||
symlinkCodegenHeaders,
|
||||
symlinkHeadersFromPath,
|
||||
@@ -18,12 +24,6 @@ const {
|
||||
symlinkThirdPartyDependenciesHeaders,
|
||||
} = require('../headers-utils');
|
||||
|
||||
// Mock all required modules
|
||||
jest.mock('../utils');
|
||||
jest.mock('../headers-mappings');
|
||||
jest.mock('node:fs');
|
||||
jest.mock('node:path');
|
||||
|
||||
describe('symlinkHeadersFromPath', () => {
|
||||
let mockUtils;
|
||||
let mockFs;
|
||||
|
||||
+16
-13
@@ -10,17 +10,6 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
configureAppForSwift,
|
||||
createHardlinks,
|
||||
findXcodeProjectDirectory,
|
||||
generateCodegenArtifacts,
|
||||
prepareHeaders,
|
||||
runIosPrebuild,
|
||||
runPodDeintegrate,
|
||||
setBuildFromSource,
|
||||
} = require('../prepare-app-utils');
|
||||
|
||||
// Mock child_process module
|
||||
jest.mock('node:child_process');
|
||||
|
||||
@@ -33,8 +22,11 @@ jest.mock('../headers-utils');
|
||||
// Mock prepare-app-dependencies-headers module
|
||||
jest.mock('../prepare-app-dependencies-headers');
|
||||
|
||||
// Mock codegen executor module
|
||||
jest.mock('../../codegen/generate-artifacts-executor');
|
||||
// Mock codegen executor module. Automocking loads the real module, which reads
|
||||
// package.json through the mocked `fs`.
|
||||
jest.mock('../../codegen/generate-artifacts-executor', () => ({
|
||||
execute: jest.fn(),
|
||||
}));
|
||||
|
||||
// Mock path module for absolute paths
|
||||
jest.mock('node:path', () => {
|
||||
@@ -46,6 +38,17 @@ jest.mock('node:path', () => {
|
||||
};
|
||||
});
|
||||
|
||||
const {
|
||||
configureAppForSwift,
|
||||
createHardlinks,
|
||||
findXcodeProjectDirectory,
|
||||
generateCodegenArtifacts,
|
||||
prepareHeaders,
|
||||
runIosPrebuild,
|
||||
runPodDeintegrate,
|
||||
setBuildFromSource,
|
||||
} = require('../prepare-app-utils');
|
||||
|
||||
describe('createHardlinks', () => {
|
||||
let mockSymlinkReactNativeHeaders;
|
||||
let mockSymlinkThirdPartyDependenciesHeaders;
|
||||
|
||||
@@ -23,10 +23,16 @@ const getPackagesMock = jest.fn();
|
||||
const updateHermesVersionsToPrebuiltMock = jest.fn();
|
||||
const getBranchName = jest.fn();
|
||||
|
||||
import type {BuildType} from '../../releases/utils/version-utils';
|
||||
|
||||
const {REPO_ROOT} = require('../../shared/consts');
|
||||
const {publishNpm} = require('../publish-npm');
|
||||
const path = require('node:path');
|
||||
|
||||
// Required on each call, so that publish-npm picks up the mocks and module
|
||||
// registry that each test sets up after this file loads.
|
||||
const publishNpm = (buildType: BuildType): Promise<void> =>
|
||||
require('../publish-npm').publishNpm(buildType);
|
||||
|
||||
let consoleLog;
|
||||
|
||||
describe('publish-npm', () => {
|
||||
|
||||
@@ -8,11 +8,6 @@
|
||||
* @format
|
||||
*/
|
||||
|
||||
const {
|
||||
getTagsFromCommitMessage,
|
||||
publishUpdatedPackages,
|
||||
} = require('../publish-updated-packages');
|
||||
|
||||
const getPackagesMock = jest.fn();
|
||||
const execSync = jest.fn();
|
||||
const execMock = jest.fn();
|
||||
@@ -23,6 +18,11 @@ jest.mock('shelljs', () => ({exec: execMock}));
|
||||
jest.mock('../../shared/monorepoUtils', () => ({
|
||||
getPackages: getPackagesMock,
|
||||
}));
|
||||
|
||||
const {
|
||||
getTagsFromCommitMessage,
|
||||
publishUpdatedPackages,
|
||||
} = require('../publish-updated-packages');
|
||||
// $FlowFixMe[cannot-write]
|
||||
global.fetch = fetchMock;
|
||||
|
||||
|
||||
@@ -10,6 +10,10 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
// @octokit/rest is ESM-only, which Jest can't load, and these tests pass their
|
||||
// own client.
|
||||
jest.mock('@octokit/rest', () => ({Octokit: jest.fn()}));
|
||||
|
||||
const {
|
||||
getReleaseAssetMap,
|
||||
uploadReleaseAssetsForDotSlashFile,
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
* @format
|
||||
*/
|
||||
|
||||
const {getNpmInfo, publishPackage} = require('../npm-utils');
|
||||
|
||||
const execMock = jest.fn();
|
||||
const getCurrentCommitMock = jest.fn();
|
||||
const exitIfNotOnGitMock = jest.fn();
|
||||
@@ -23,6 +21,8 @@ jest.mock('./../scm-utils', () => ({
|
||||
exitIfNotOnGit: exitIfNotOnGitMock,
|
||||
}));
|
||||
|
||||
const {getNpmInfo, publishPackage} = require('../npm-utils');
|
||||
|
||||
describe('npm-utils', () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
* @format
|
||||
*/
|
||||
|
||||
const {isTaggedLatest} = require('../scm-utils');
|
||||
|
||||
let execResult = null;
|
||||
|
||||
jest
|
||||
@@ -37,6 +35,8 @@ jest
|
||||
),
|
||||
}));
|
||||
|
||||
const {isTaggedLatest} = require('../scm-utils');
|
||||
|
||||
describe('scm-utils', () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
|
||||
Reference in new issue
Block a user