【问题标题】:How to spy a predefined object with sinon.js如何使用 sinon.js 监视预定义对象
【发布时间】:2013-06-20 22:12:17
【问题描述】:

我正在尝试使用 sinon.js 来监视 window.document。我要做的是:

var document = {
    getElementById = function() {}
}

sinon.spy(document, "getElementById").withArgs("foo").returnValues = ["bar"];

我对这次通话的期望是: 当使用参数“foo”调用 document.getElementById 时,该函数必须返回“bar”。我的错误是什么?

如果我像这样自己定义 getElementById,我会得到预期的结果:

document.getElementById = function(param) {
    if (param === "foo") return "bar";
}

【问题讨论】:

    标签: javascript testing sinon spy


    【解决方案1】:

    您只能记录对函数的调用并检查是否调用了 tey,但不能更改函数的行为。来自withArgs 的文档:

    创建一个仅在收到参数时记录调用的间谍 匹配传递给 withArgs 的那些

    你要找的是sinon.stub:

    sinon.stub(document, 'getElementById').withArgs('foo').returns(['bar'])
    

    【讨论】:

    • @Aykut Yaman:你在这里所做的document.getElementById = function(param) { if (param === "foo") return "bar";} 正在永久替换原来的getElementById 功能。 stub 所做的同样的事情。唯一的区别是在存根的情况下,您可以选择restore 他的原始功能。
    猜你喜欢
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多