检查调用 Sinon Stub 的参数是什么?
有几种方法可以检查在 Sinon 中调用 Stub 的参数是什么,我们推荐的方法是 calledWith()
和相关的助手,以及 getCall()
。
调用With()
calledWith
如果使用提供的参数至少调用了一次存根,则将返回 true,如果存根函数的参数多于应有的参数,但定位正确,该函数也可以返回 true。
const sinon = require('sinon');
const math = {
add: (a, b) => { return a + b; }
};
let stub = sinon.stub(math, 'add');
math.add(1, 2);
stub.calledWith(1, 2); // true
stub.calledWith(0, 5); // false
// Reset the stub
sinon.restore();
stub = sinon.stub(math, 'add');
math.add(1, 2, 3, 4, 5); // Called with 3 extra args
stub.calledWith(1, 2); // true, because 1 and 2 are in the same position as the stub call
调用 OnceWith() 和 alwaysCalledWith()
calledOnceWith()
如果 Stub 只被调用一次 , 并且一个调用的参数使用相同的语义匹配 calledWith()
。alwaysCalledWith()
如果每次调用 Stub 时,参数都匹配,则返回 true。
const sinon = require('sinon');
const math = {
add: (a, b) => { return a + b; }
};
let stub = sinon.stub(math, 'add');
math.add(1,2);
stub.calledOnceWith(1,2); // true
math.add(1,2);
stub.calledOnceWith(1, 2); // false, as add() has been called twice now.
stub.alwaysCalledWith(1, 2); // true
math.add(3, 4);
stub.alwaysCalledWith(1, 2); // false
getCall().args
getCall()
函数 返回有关给定调用 Stub 的信息。getCall(i)
返回一个包含 args
,returnValue
等第 i 次调用 Stub。getCall()
使用基于 0 的索引,这意味着访问您使用的第一个调用 getCall(0)
。
const sinon = require('sinon');
const math = {
add: (a, b) => { return a + b; }
};
let stub = sinon.stub(math, 'add');
math.add(1, 2);
math.add(3, 4);
stub.getCall(0).args; // [1, 2]
stub.getCall(1).args; // [3, 4]
自从 getCall().args
将参数作为 JavaScript 数组返回,然后您可以使用 JavaScript 中比较数组 :
// Using vanilla JavaScript
function argsEqual(call, arr) {
return call.args.every((el, i) => el === arr[i]);l
}
argsEqual(stub.getCall(0), [1, 2]); // true
argsEqual(stub.getCall(1), [1, 2]); // false
// Using Node.js' assert lib:
assert.deepEqual(stub.getCall(0).args, [1, 2]);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论