javascript - 如何测试带有回调函数的组件

标签 javascript unit-testing react-native jestjs enzyme

我有这样一个组件:

    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={[函数 mockConstructor]} 这是它收到的内容:onButtonPress={[Function myCallbackFunction]}

我做错了什么?

最佳答案

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

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

在不更改组件代码的情况下,您可以检查组件 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)}
        />
    );
});

关于javascript - 如何测试带有回调函数的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59005271/

相关文章:

typescript - 如何使用 Firebase Firestore 在客户端上缓存 getDownloadUrl() 调用?

javascript - 如何使用实时更新数据(SignalR)

ruby-on-rails - rails : How do I write tests for a ruby module?

unit-testing - Grails/Spock : How to mock single method within class where method is called from within the class itself?

c# - 对返回集合的方法进行单元测试

android - 流程发布资源

javascript - React Context API,更新上下文

javascript - 将 javascript 变量转换为 ruby​​ 变量

javascript - document 和 document.cookie 之间的范围差异

javascript - Parsley JS 2.x - 禁用不可见字段的验证