3

I'm trying to spy window.document with sinon.js. What I do is this:

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

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

What I expect from this call is this: When document.getElementById is called with the argument "foo" the function must return "bar". What's my error?

If I define getElementById by myself like this I get the expected result:

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

1 回答 1

4

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

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

您正在寻找的是sinon.stub

sinon.stub(document, 'getElementById').withArgs('foo').returns(['bar'])
于 2013-06-25T07:16:02.063 回答