简体   繁体   English

如何使用回调函数测试组件

[英]How to test a component with callback function

I have a component like this:我有一个这样的组件:

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

I want to test the ListEmptyComponent.我想测试 ListEmptyComponent。 Inside my test I try to mock myCallbackFunction and make sure ListEmptyComponent is equal to MyCustomComponent :在我的测试中,我尝试模拟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}
            />
        );
    });

The test fails because this is what it expects: onButtonPress={[Function mockConstructor]} and this is what it receives: onButtonPress={[Function myCallbackFunction]}测试失败,因为这是它所期望的: onButtonPress={[Function mockConstructor]}而这是它收到的: onButtonPress={[Function myCallbackFunction]}

What am I doing wrong?我究竟做错了什么?

As the code is defined, the function myCallbackFunction is a private function, so you are not going to be able to mock it.在定义代码时,函数myCallbackFunction是一个私有函数,因此您将无法模拟它。

In your test, you are defining a mock function with the same name of the private function, but that does not mean they are the same function (they are not).在您的测试中,您定义了一个与私有函数同名的模拟函数,但这并不意味着它们是相同的函数(它们不是)。

Without changing the component code, you could check that the component ListEmptyComponent receives a function in the onButtonPress property:在不更改组件代码的情况下,您可以检查组件ListEmptyComponentonButtonPress属性中接收到一个函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM