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";
}
Aykut Yaman
  • 80
  • 2
  • 9

1 Answers1

4

You can only record calls on function and check that tey was called, but never change the behavior of the function. From the doc for withArgs:

Creates a spy that only records calls when the received arguments matche those passed to withArgs

Whar you are looking for is a sinon.stub:

sinon.stub(document, 'getElementById').withArgs('foo').returns(['bar'])
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
  • @Aykut Yaman: what you are doing here `document.getElementById = function(param) { if (param === "foo") return "bar";}` is replacing the original `getElementById` function permanently. The same thing which is done by `stub`. The only difference being in case of stubs, you have the option to `restore` he original function. – Pawan Jul 17 '13 at 08:55