如何使用Jest和酶测试此功能?
addProducts = id => {
toast.success("Product added", {
position: toast.POSITION.TOP_RIGHT
});
history.push(`/product/${id}`);
};
我正在使用此代码段,但这还不够...
it("Must return added addProduct with success message", () => {
const componente = shallow(<AddProduct />);
const spy = jest.spyOn(wrapper.instance(), "addProducts");
expect(spy).toBeTruthy();
});
[如果您要进行我们的单元测试,则可以在此处进行两件事的测试:
1)用正确的参数调用toast.success()
,即'Product added'
和对象{ position: toast.POSITION.TOP_RIGHT }
2)history.push()
被调用,并且history.push被正确调用。
对于以上两种情况,您都必须对它们两个都调用jest.spyOn()
,然后检查它们是否被调用过一次。
expect(toastSpy).toBeCalledTimes(1);
expect(historyPushSpy).toBeCalledTimes(1);
此外,您需要断言上述模拟被正确调用了。
const toastSpyCall = toastSpy.mock.calls[0][0];
// expect(...).toBe(....)