【问题标题】:How to test a component with callback function如何使用回调函数测试组件
【发布时间】:2019-11-23 06:50:41
【问题描述】:

我有一个这样的组件:

    export const MyList = props => {

      const myCallbackFunction = () => {
        // do stuff
      };

      const ListEmptyComponent = (
        <MyCustomComponent
            text="sample text"
            onButtonPress={myCallbackFunction}
        />
      );

      return (
        <FlatList
         data={DATA}
         renderItem={({ item }) => (<Item title={item.title} />)}
         ListEmptyComponent={ListEmptyComponent} />
       );
    };

我想测试 ListEmptyComponent。在我的测试中,我尝试模拟 myCallbackFunction 并确保 ListEmptyComponent 等于 MyCustomComponent

    it("should display the MyCustomComponent", () => {
        const myCallbackFunction = jest.fn();
        const component = renderComponent();

        expect(
            component
                .find(FlatList)
                .prop("ListEmptyComponent")
        ).toEqual(
            <MyCustomComponent
                text="sample text"
                onButtonPress={myCallbackFunction}
            />
        );
    });

测试失败,因为这是它所期望的: onButtonPress={[Function mockConstructor]} 这就是它收到的内容:onButtonPress={[Function myCallbackFunction]}

我做错了什么?

【问题讨论】:

  • 好像myCallbackFunction组件使用不是你从props传递过来的,所以你可以考虑把组件改成使用onButtonPress={props.myCallbackFunction}

标签: javascript unit-testing react-native jestjs enzyme


【解决方案1】:

由于代码已定义,函数myCallbackFunction 是私有函数,因此您无法模拟它。

在您的测试中,您定义了一个与私有函数同名的模拟函数,但这并不意味着它们是同一个函数(它们不是)。

在不更改组件代码的情况下,您可以检查组件ListEmptyComponent 是否接收到onButtonPress 属性中的函数:

it("should display the MyCustomComponent", () => {
    const myCallbackFunction = jest.fn();
    const component = renderComponent();

    expect(
        component
            .find(FlatList)
            .prop("ListEmptyComponent")
    ).toEqual(
        <MyCustomComponent
            text="sample text"
            onButtonPress={expect.any(Function)}
        />
    );
});

【讨论】:

  • @mgarica 非常感谢。有效。我收到警告的唯一问题是:警告:失败的道具类型:无效的道具myCallbackFunction 类型为object 提供给MyCustomComponent ,预期function。在 MyCustomComponent 中不知道为什么因为我传递了一个它应该期望的函数
猜你喜欢
  • 2020-03-23
  • 1970-01-01
  • 2018-11-15
  • 2022-01-24
  • 2020-11-26
  • 2021-04-02
  • 1970-01-01
  • 2019-09-21
  • 1970-01-01
相关资源
最近更新 更多