Problems assigning properties to a sinon.stub(obj, "Method") stub.

1,649 views
Skip to first unread message

Peter Havens

unread,
Aug 29, 2012, 5:25:41 PM8/29/12
to sin...@googlegroups.com
I may misunderstand how sinon works, but I'd like to do something like the following in a test:
 
# ...
stub = sinon.stub(mod.submod, "Class");
stub.method = sinon.stub();
# ...exercise SUT
# assert that stub.method was called
stub.restore();
# ...

However, in my SUT, when I do:

obj = new mod.submod.Class();
obj.method();

...I get an error about `method` not being defined on `obj`. The `obj` object appears to be a `proxy`, and that `proxy` doesn't have the `method` defined on it. Is there a way to "chain" stubs like this?

Thanks,
Pete

Christian Johansen

unread,
Aug 31, 2012, 4:26:03 AM8/31/12
to sin...@googlegroups.com
Hi Peter,

It's _almost_ correct :) The clue is that "Class" is a function, not an object, so to
create stubbed methods for its instances, you need to stub on the prototype, OR
return stubbed objects from the constructor.

Approach #1: Stub prototype

# ...
stub = sinon.stub(mod.submod.Class.prototype, "method");
# ...exercise SUT
# assert that stub.method was called
stub.restore();
# ...
Approach #2: Stub returned objects from constructor (this way you must mimic
the entire API being used):

# ...
stub = sinon.stub(mod.submod, "Class").returns({ method: sinon.stub() }, ...);
# ...exercise SUT
# assert that stub.method was called
stub.restore();
# ...

Christian
--
MVH
Christian
Reply all
Reply to author
Forward
0 new messages