用Jest和酶测试功能?

问题描述 投票:0回答:1

如何使用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();
});
reactjs jestjs enzyme
1个回答
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(....)
© www.soinside.com 2019 - 2024. All rights reserved.