【问题标题】:Test functions with Jest and Enzyme?用 Jest 和 Enzyme 测试函数?
【发布时间】:2019-12-30 23:56:05
【问题描述】:

如何使用 Jest 和 Enzyme 测试此功能?

addProducts = id => {
    toast.success("Product added", {
        position: toast.POSITION.TOP_RIGHT
    });
    history.push(`/product/${id}`);
};

我正在使用这个 sn-p 的代码,但它还不够......

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】:

    如果您要进行我们的单元测试,您可以在这里测试两件事:

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

    【讨论】:

      猜你喜欢
      • 2018-09-08
      • 2017-11-26
      • 2018-10-31
      • 2017-11-30
      • 2018-10-20
      • 1970-01-01
      • 2020-08-27
      • 2017-11-10
      • 1970-01-01
      相关资源
      最近更新 更多