用Jest和酶测试功能?

时间:2019-12-30 23:56:05

标签: reactjs enzyme jest

如何使用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 个答案:

答案 0 :(得分:0)

如果您要进行单元测试,则可以在此处进行两件事的测试:

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(....)