gpt4 book ai didi

javascript - Sinon Stub JavaScript 方法链

转载 作者:行者123 更新时间:2023-11-30 20:18:44 24 4
gpt4 key购买 nike

我正在寻找使用 sinon stub 来测试下面的方法链:

driver.manage().window().setSize()

我发现了一个相关问题,它解释了如何访问链下的一种方法,但这似乎并没有让我访问任何其他方法。

t.context.webdriver = sinon.stub(new WebDriver)
sinon.stub(t.context.webdriver, "manage", () => {
return {
window: sinon.stub().returns();
};
})

返回错误

Error: this._driver.manage(...).window(...).setSize is not a function

如何 stub 多级方法链?

最佳答案

我不确定您要测试什么,但错误是因为您的 stub 返回的对象没有 window() 函数或 设置大小()。链之所以起作用,是因为链的每个部分都返回一些与下一次调用匹配的方法。所以如果你在链的早期填充一些东西,你需要确保你返回的东西有那些方法。也许这涉及传回原始返回,或者您可能伪造整个链条。

这是一个至少不会抛出的例子:

const sinon = require('sinon')

// some fake object that maybe looks like what you have
let driver = {
manage(){ return this},
window() { return this},
setSize() {console.log("size set")}
}

// stubb manage and now you're resposible for the whole chain
sinon.stub(driver, "manage").callsFake(() => {
console.log("called")
return {
window(){
return { setSize: sinon.stub().returns() }
}
};
})

当然,根据您要测试的内容,可能会有很多变化。

关于javascript - Sinon Stub JavaScript 方法链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51682449/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com