如何在 Reactjs 中模拟导入的组件

How to mock imported component in Reactjs

我需要为包含子 <Example/> 组件的包装器组件编写测试。 <Example/> 中正在进行大量嘲笑。我想要实现的是将模拟的 <Example/> 放入 <Parent/> 中,而不必再次进行模拟。

伪代码 test('test', () => { //there somehow need to swap component that is imported inside Parent render(<Parent/>) })

如果您使用的是功能组件,您可以通过在测试文件的顶部添加以下代码来模拟子组件:

// Each occurrence of ChildComponent in the tested component
// will be mocked with a div, with a data-testid attribute and
// its props in a data-props attribute
jest.mock('/path/to/child/ChildComponent', () => ({
  __esModule: true,
  ChildComponent: (props: any) => (
    <div data-testid="mocked-child-component" data-props={JSON.stringify(props)}>
      Mocked Child Component
    </div>
  ),
}));

所以你可以在测试父组件时测试ChildComponent存在,通过搜索data-testid(或者div中的文本),并检查传递给ChildComponent的props被测组件是正确的:

const getProps = (element: HTMLElement): Record<string, unknown> => JSON.parse(element.getAttribute('data-props'));

[...]

// check that parent component is passing correct props to its child
rtl = render(<ParentComponent />));
expect(getProps(rtl.getByTestId('mocked-children-component'))).toEqual({...});