Files
react-native/packages/react-native/jest/mockNativeComponent.js
T
Tim Yung 1fd9508ecc RN: Refactor Jest Default Mocks (#51669)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51669

Refactors the default mocks initialized in `packages/react-native/jest/setup.js` so that each mock is defined in its own file.

This provides several benefits, including:

- The ability to use `import` statements without worrying about eager initialization of dependencies before `globals` is setup.
- The ability to verify mocks export the same types as the actual module, using a new Flow-typed `mock` helper function.
- The ergonomic of implementing mocks with more complex logic, without having to split them out into a separate module (e.g. `mockModal`, `mockScrollView`).

As part of this migration, I also fixed any minor discrepancies to match the actual type definition. For more involved discrepancies (e.g. missing methods), I added type suppressions for now to minimize breaking changes.

Changelog:
[General][Changed] - Improved default mocking for Jest unit tests.

Reviewed By: javache

Differential Revision: D75575421

fbshipit-source-id: 98d60e10b753f1505ffdccf5f12f5d3ef306ebb5
2025-05-29 07:52:38 -07:00

52 lines
1.3 KiB
JavaScript

/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
import type {HostInstance} from '../src/private/types/HostInstance';
import * as React from 'react';
import {createElement} from 'react';
let nativeTag = 1;
type MockNativeComponent<TProps: {...}> = component(
ref?: ?React.RefSetter<HostInstance>,
...props: TProps
);
export default function mockNativeComponent<TProps: {...}>(
viewName: string,
): MockNativeComponent<TProps> {
const Component = class extends React.Component<TProps> {
_nativeTag: number = nativeTag++;
render(): React.Node {
// $FlowIgnore[not-a-function]
// $FlowIgnore[prop-missing]
return createElement(viewName, this.props, this.props.children);
}
// The methods that exist on host components
blur: () => void = jest.fn();
focus: () => void = jest.fn();
measure: () => void = jest.fn();
measureInWindow: () => void = jest.fn();
measureLayout: () => void = jest.fn();
setNativeProps: () => void = jest.fn();
};
if (viewName === 'RCTView') {
Component.displayName = 'View';
} else {
Component.displayName = viewName;
}
return Component;
}