Sinon.js 合并 calledWith 次数

Sinon.js combining calledWith number of times

我知道 sinon.js 你可以测试间谍被调用了一定次数:

sinon.assert.calledTwice(mySpy.someMethod);

并且您可以测试是否使用特定参数调用了间谍:

sinon.assert.calledWith(mySpy.someMethod, 1, 2);

但是如何将它们结合起来以测试某个方法是否被调用了特定次数并带有特定参数?理论上是这样的:

sinon.assert.calledTwiceWith(mySpy.someMethod, 1, 2);

A spy 提供对使用 getCall() and getCalls(). Each Spy call can be tested using methods like calledWithExactly():

进行的调用的访问
import * as sinon from 'sinon';

test('spy', () => {

  const spy = sinon.spy();
  spy(1, 2);
  spy(3, 4);
  expect(spy.callCount).toBe(2);
  expect(spy.getCall(0).calledWithExactly(1, 2)).toBe(true);
  expect(spy.getCall(1).calledWithExactly(3, 4)).toBe(true);

});

遗憾的是,Sinon 没有检查您正在查找的内容的功能,尤其是在您不知道或不关心调用顺序的情况下。但是,它确实允许您在每次单独调用函数时进行检查。结果,虽然有点不雅,但你可以自己计算函数被预期参数调用的次数。

使用spy.getCalls()获取间谍调用的数组,这些调用是spy call objects的实例。每次调用都允许您使用 call.args(不是 call.args())访问传递给间谍的参数数组。

test('spy', () => {
  const spy = sinon.spy();
  spy(1, 2);
  spy(1, 2);
  spy(3, 4);

  const wantedCalls = spy.getCalls().filter(
    (call) => call.args.length === 2 && call.args[0] === 1 && call.args[1] === 2
  );

  expect(wantedCalls.length).toEqual(2);
});

更干净一点,如 ,您可以调用 call.calledWithExactly() 来检查收到的特定调用的参数:

test('spy', () => {
  const spy = sinon.spy();
  spy(1, 2);
  spy(1, 2);
  spy(3, 4);

  const wantedCalls = spy.getCalls().filter(
    (call) => call.calledWithExactly(1, 2)
  );

  expect(wantedCalls.length).toEqual(2);
});