我在 stub 我想在 typescript 中测试的方法所使用的方法时遇到问题。为了清楚起见,我在示例中删除了许多方法本身,但基本上我有一个调用 getService
方法的 getServiceWithRetry
方法。
即。
export function getServiceWithRetry(name:string, triesLeft:number) {
//do stuff
getService(name)
//do more stuff
}
export function getService(name:string) {
//lookup stuff
}
这作为 Lookup
导入到我的测试中。如果我在测试中调用 getService
,我可以成功地消除 getService 方法,但是当我运行 getServiceWithRetry
时,它会调用实际的 getService
方法而不是 stub 。有谁知道我做错了什么?
it("test", function(done) {
let serviceStub = sinon.stub(Lookup, 'getService')
serviceStub.returns(Promise.resolve("resolved"))
//this uses the stub
Lookup.getService("name").then(function(value) {
console.log("success: "+value)
}, function(error) {
console.log("error: "+error)
})
//this calls the actual method, not the stub as I would expect it to
Lookup.getServiceWithRetry("serviceName", 4).then(function(value) {
console.log("success: "+value)
}, function(error) {
console.log("error: "+error)
})
done()
})
注意:对于那些不熟悉 bluebird Promise 的人来说,.then(function(value){}, function(error){})
方法会处理 Promise 成功以及 Promise 失败时发生的情况。被拒绝。
最佳答案
您需要更改:
export function getServiceWithRetry(name:string, triesLeft:number) {
//do stuff
getService(name)
//do more stuff
}
至:
export function getServiceWithRetry(name:string, triesLeft:number) {
//do stuff
this.getService(name)
//do more stuff
}
这样,当您调用 Lookup.getServiceWithRetry()
时,getService()
调用将指向 Lookup.getService()
而不是getService()
驻留在您从中导出的模块中。
关于javascript - Sinon - 如何 stub 我想要测试的方法调用的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39988909/