我想知道在 sinon.js 中是否有可能只对一个方法 stub 一次?
例如:
sinon.stub(module, 'randomFunction', 'returnValue/function');
在我的测试中,这个 module.randomFunction 将被多次调用在同一个测试中,但我只希望 stub 触发一次然后恢复它所以函数恢复正常行为。
模拟真实代码:
myModule.putItem(item, function (err, data) {
if (err) {
// do stuff
return callback();
} else {
// do other stuff
return callback(null, data);
}
});
第一次我想触发错误,其他时候我只是想让它继续真正的流程。
这在 sinon 中可行吗?
亲切的问候,
吉米
编辑:我根据@Grimurd 的回答发布了我为我的问题找到的解决方案
最佳答案
是的,这是可能的。假设您使用 mocha 作为测试框架。
describe('some tests', function() {
afterEach(function() {
sinon.restore();
})
it('is a test with a stub', function() {
// This gets restored after each test.
sinon.stub(module, 'randomFunction', 'returnValue/function');
})
})
查看 sinon sandbox api了解更多信息。
更新
回答你的实际问题,
describe('some tests', function() {
afterEach(function() {
sinon.restore();
})
it('is a test with a stub', function() {
// This gets restored after each test.
sinon.stub(module, 'randomFunction')
.onFirstCall().returns('foo')
.onSecondCall().returns('bar')
.onThirdCall().returns('foobar');
})
})
记录于 http://sinonjs.org/docs/搜索 stub.onCall(n)
更新 2:由于 v5 sinon 现在默认创建沙箱,因此不再需要显式创建沙箱。 See the migration guide from v4 to v5 for more information
关于javascript - Sinon.js,只 stub 一个方法一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37343232/