【问题标题】:How to mock imported component in Reactjs如何在 Reactjs 中模拟导入的组件
【发布时间】:2021-08-25 04:37:52
【问题描述】:

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

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

【问题讨论】:

  • 显示代码。你试过什么?你得到了什么?
  • @slideshowp2 子组件有很多需要模拟的逻辑,但我不想在它自己的测试和测试父组件时重复测试它
  • 不清楚。测试父组件时可以mock复杂的子组件。

标签: javascript reactjs testing jestjs react-testing-library


【解决方案1】:

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

// 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({...});

【讨论】:

    猜你喜欢
    • 2021-09-22
    • 1970-01-01
    • 2018-10-14
    • 2020-01-13
    • 2017-04-09
    • 1970-01-01
    • 2018-03-01
    • 2023-04-07
    • 2019-03-05
    相关资源
    最近更新 更多