Sinon Stub JavaScript方法链

时间:2018-08-04 04:33:55

标签: javascript unit-testing sinon

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

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

如何对多级方法链进行存根处理?

1 个答案:

答案 0 :(得分:1)

我不确定您要测试什么,但错误是由于存根返回的对象没有window()函数或setSize()而导致的。链之所以起作用,是因为链的每个部分都使用匹配下一个调用的方法返回某些内容。因此,如果您将某些东西塞进了链的早期,则需要确保返回的内容具有这些方法。也许这涉及传回原始回报,或者您伪造了整个链条。

以下是至少不会抛出的示例:

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() }
        }
    };
})

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