首页 > 解决方案 > 你如何在 Jasmine/Jest 中对独特的方法调用进行单元测试?

问题描述

我的应用程序中有代码,其中某个函数被调用了 n 次(让我们调用这个函数foo)。运行时期望是每次调用foo都是唯一的(使用一组唯一的参数调用)。foo由于多次使用相同的参数集调用,我的应用程序中有一个最近的错误清单。

我想编写一个测试用例,我可以在其中断言foo使用一组特定的参数唯一地调用过一次,但我不知道如何在 Jasmine/Jest 中这样做。

我知道 Jasmine 有toHaveBeenCalledOnceWith匹配器,但它断言它foo被称为“恰好一次,并且完全带有特定的参数”,这不是我在这种情况下要寻找的。

标签: javascriptunit-testingjestjsjasmine

解决方案


您可以组合toHaveBeenCalledWith()toHaveBeenCalledTimes()获得您想要的行为,您只需要拥有与toHaveBeenCalledWith()您期望的呼叫数量一样多的 s :

例如:

describe("test", () => {
  it("should call not more than unique", () => {
     spyOn(callsFoo, 'foo');
     callsFoo.somethingThatCallsFoo();
     expect(callsFoo.foo).toHaveBeenCalledTimes(2);
     expect(callsFoo.foo).toHaveBeenCalledWith({...someArgs});
     expect(callsFoo.foo).toHaveBeenCalledWith({...otherUnique});
  });
})

如果重复调用不是唯一的,这将失败。


推荐阅读