javascript - Sinon - 如何 stub 我想要测试的方法调用的方法

标签 javascript typescript sinon

我在 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/

相关文章:

node.js - 在 Node.js 中对 S3 上传进行 stub

node.js - 在我的测试中,使用 stub 函数未捕获事件

带 cookies 的 JavaScript 倒计时器一分钟后停止

javascript - 如何使用 MutationObserver 获取标签类型?

javascript - 一旦用户鼠标离开文本字段就运行函数

javascript - jquery 如何使用 Regex 选择 <option>

angular - observables 中的promise<void> 等价于什么?

typescript - 如何检查强类型对象是否包含 TypeScript 中的给定键而不提示?

javascript - 如何确保 typescript 模块符合接口(interface)

javascript - 西农 fakeserver url 正则表达式