你能在 Jasmine 中结合使用 toHaveBeenCalledWith 和 toHaveBeenCalledTimes 吗?

Can you combine toHaveBeenCalledWith and toHaveBeenCalledTimes in Jasmine?

我在 Jasmine 单元测试中使用这两个单独的断言。

expect(spyFunction).toHaveBeenCalledWith(expectedArgument);
expect(spyFunction).toHaveBeenCalledTimes(expectedCount);

如果我理解正确,这些将证实以下内容。

我想做的是确认该函数被调用 expectedArgumentexpectedCount 次。换句话说,我只想计算参数匹配的调用次数。

我意识到我可以用假货自己数数...

var callCount = 0;
spyOn(myInstance, 'myFunction').and.callFake(arg => {
  if (arg === expectedArgument) {
    callCount++;
  }
});

...

expect(callCount).toEqual(expectedCount);

...但这没有以前语法的可读性,感觉像是在重新发明轮子。我没有那么多使用 Jasmine,所以我想知道我是否遗漏了什么。

有没有办法使用内置的 Jasmine 匹配器来进行断言?或者,是否有另一种方法来获得类似可读的语法?

您可以使用 calls 从间谍那里获得更详细的信息。您可以这样查看每个调用及其参数:

expect(spyFunction.calls.count()).toBe(2)
expect(spyFunction.calls.argsFor(0)).toEqual(/* args for 1st call */)
expect(spyFunction.calls.argsFor(1)).toEqual(/* args for 2nd call */)

详情见Jasmine docs