我有这样一个组件:
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/