Sinon stub withExactArgs?
Sinon stub withExactArgs?
Sinon mocks 有一个 withExactArgs 方法,它断言传递给相关方法的参数数量。有没有办法使用存根来实现这种行为?
现在他们似乎是这样工作的:
const methodStub = stub();
methodStub.withArgs().returns(1);
console.log(methodStub()); // prints 1
console.log(methodStub({})); // also prints 1
我想要精确参数匹配。我研究过向 sinon 添加自定义行为,但没有成功。我真的不知道接下来要尝试什么。
我知道我可以在调用之后检查参数,但我觉得以这种方式编写的测试的清洁度不佳。
此外,这个在 SO 上相当受欢迎的 post 让我 非常 困惑:Can sinon stub withArgs match some but not all arguments。引用:
if I use method.get.withArgs(25).calls... then it does not match either, because withArgs() matches all arguments
我似乎观察到与 Sinon v6 完全相反的情况,这正是 OP 正在寻找的行为...
链接问题中的这个陈述是不正确的:
withArgs()
matches all arguments
withArgs
不匹配所有参数。我添加了一个 answer 和详细信息。
withExactArgs
对于 stub
has been discussed but never implemented.
所以是的,调用后检查参数,将 callsFake
与自定义函数一起使用,添加自定义行为,或使用 mock
而不是 stub
sinon
中的当前选项,用于断言使用精确参数调用方法。
例如,问题中的存根看起来应该只 return 1
如果调用时没有参数,可以使用 callsFake
:
test('stub exact args', () => {
const stub = sinon.stub();
stub.callsFake((...args) => {
if (args.length === 0) {
return 1;
}
return 'default response';
});
expect(stub()).toBe(1); // SUCCESS
expect(stub({})).toBe('default response'); // SUCCESS
});
Sinon mocks 有一个 withExactArgs 方法,它断言传递给相关方法的参数数量。有没有办法使用存根来实现这种行为?
现在他们似乎是这样工作的:
const methodStub = stub();
methodStub.withArgs().returns(1);
console.log(methodStub()); // prints 1
console.log(methodStub({})); // also prints 1
我想要精确参数匹配。我研究过向 sinon 添加自定义行为,但没有成功。我真的不知道接下来要尝试什么。
我知道我可以在调用之后检查参数,但我觉得以这种方式编写的测试的清洁度不佳。
此外,这个在 SO 上相当受欢迎的 post 让我 非常 困惑:Can sinon stub withArgs match some but not all arguments。引用:
if I use method.get.withArgs(25).calls... then it does not match either, because withArgs() matches all arguments
我似乎观察到与 Sinon v6 完全相反的情况,这正是 OP 正在寻找的行为...
链接问题中的这个陈述是不正确的:
withArgs()
matches all arguments
withArgs
不匹配所有参数。我添加了一个 answer 和详细信息。
withExactArgs
对于 stub
has been discussed but never implemented.
所以是的,调用后检查参数,将 callsFake
与自定义函数一起使用,添加自定义行为,或使用 mock
而不是 stub
sinon
中的当前选项,用于断言使用精确参数调用方法。
例如,问题中的存根看起来应该只 return 1
如果调用时没有参数,可以使用 callsFake
:
test('stub exact args', () => {
const stub = sinon.stub();
stub.callsFake((...args) => {
if (args.length === 0) {
return 1;
}
return 'default response';
});
expect(stub()).toBe(1); // SUCCESS
expect(stub({})).toBe('default response'); // SUCCESS
});