我有一个我正在存根的函数,它被调用多个参数。我只想检查第一个参数。其余的都是回调函数,所以我想把它们放在一边。因此,我可能有以下2个调用,以ajax为例:
method.get = sinon.stub();
method.get(25,function(){/* success callback */},function(){/* error callback */});
method.get(10,function(){/* success callback */},function(){/* error callback */});
我不能使用< code>method.get.calls...因为它不会区分第一个< code>get(25)和第二个< code>get(10)。但是如果我使用< code>method.get.withArgs(25)。打电话...那么它也不匹配,因为< code>withArgs()匹配所有参数,而this不匹配(而且永远也不可能,使用那样的回调)。
如何让sinon存根仅根据第一个参数检查和设置响应?
https://sinonjs.org/releases/latest/matchers/#sinonmatchany
您可以使用正统:
method.get.withArgs(25, sinon.match.any, sinon.match.any);
withArgs
可用于匹配部分但不是所有参数。
具体来说, 方法 25 将
只检查第一个参数。
这是不正确的:
withArgs()
匹配所有参数
当调用带有Args的时,它会记住它在此处作为
matchingArguments
传递的参数。
然后当调用存根
时,它会在此处获取所有匹配的假货。
调用matchingFakes
时不带第二个参数,因此它返回所有fake,这些fake具有matchingArguments
,这些fakes与传递给matching arguments
。这意味着即使有额外的参数,当false的matchingArguments
匹配传递的参数的开头时,false也会匹配。
然后,所有匹配的fake都按matchingArguments排序。长度
和匹配最多参数的参数是被调用的参数。
以下测试确认了此行为,并通过了7年前的sinon
version1.1.0
、提出此问题时的版本1.14.0
和当前版本6.3.5
:
import * as sinon from 'sinon';
test('withArgs', () => {
const stub = sinon.stub();
stub.withArgs(25).returns('first arg is 25!');
stub.returns('default response');
expect(stub(25)).toBe('first arg is 25!'); // SUCCESS
expect(stub(25, function () { }, function () { })).toBe('first arg is 25!'); // SUCCESS
expect(stub(10, function () { }, function () { })).toBe('default response'); // SUCCESS
});
如果您只想检查第一个参数,则可以使用
method.get.withArgs(25).calledOnce
或者
method.get.calledWith(25)