sinon stub withArgs可以匹配一些但不是所有参数

dei*_*tch 57 sinon

我有一个函数我正在使用多个参数调用它.我想检查第一个参数.其余的是回调功能,所以我想让他们独自一人.因此,我可能会使用ajax作为示例进行以下2次调用:

method.get = sinon.stub();
method.get(25,function(){/* success callback */},function(){/* error callback */});         
method.get(10,function(){/* success callback */},function(){/* error callback */});
Run Code Online (Sandbox Code Playgroud)

我不能使用,method.get.calls...因为它没有区分第一个get(25)和第二个get(10).但是,如果我使用method.get.withArgs(25).calls...那么它也不匹配,因为withArgs()匹配所有参数,这不会(并且永远不会,与回调类似).

我怎样才能让sinon存根根据第一个arg进行检查和设置响应?

And*_*ord 97

https://sinonjs.org/releases/latest/matchers/#sinonmatchany

你可以使用sinon.match.any:

method.get.withArgs(25, sinon.match.any, sinon.match.any); 
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.这将是很好,如果我能做到'method.get.withFirstArgs(25)`而且只要从而为'ARG [0]``是它25`将会匹配,但我想它不存在. (3认同)
  • 效果很好![这是一个固定链接](http://sinonjs.org/releases/v3.2.1/matchers/#sinonmatchany) 到最新的`sinon.match.any` 文档。 (2认同)

Bri*_*ams 7

解决方案

withArgs 用于匹配一些但不是所有参数。

具体来说,method.get.withArgs(25) 检查第一个参数


更正

这是不正确的:

withArgs()匹配所有参数


细节

withArgs被调用时,它会记住在此处传递的参数为matchingArguments

然后当stub被调用时,它会在这里获取所有匹配的假货。

matchingFakes在没有第二个参数的情况下调用,因此它返回所有matchingArguments 与传递给stub从索引 0 开始直到matchingArguments. 这意味着即使有其他参数,当它matchingArguments匹配传递的参数的开头时,fake 也会匹配。

然后matchingArguments.length任何匹配的伪造进行排序,匹配最多参数的就是被调用的


下面的测试证实了这种行为,并通过sinon版本1.1.0从7年前的版本,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

});
Run Code Online (Sandbox Code Playgroud)