How to spy on constructors?

4,480 views
Skip to first unread message

Billy V.

unread,
Feb 10, 2013, 3:14:06 PM2/10/13
to sin...@googlegroups.com
I have some code like this
var foo = function(arg) {
};
 
var bar = function(arg) {
var baz = new foo(arg);
};
 
describe('Test', function() {
it('foo initialized by bar()', function() {
var spy = sinon.spy(foo);
bar('test');
expect(spy).to.be.called;
expect(spy).to.be.calledWith('test');
});
});

This fails because spy doesn't get called, am I approaching this correctly?


 

Erin Swenson-Healey

unread,
Feb 10, 2013, 7:51:27 PM2/10/13
to sin...@googlegroups.com
Hey Billy,

If you namespace "foo" or otherwise hang it off some object, the spy
works as you're intending it to albiet with a little tweaking.

I have not looked into the Sinon source code to determine why passing
the constructor reference to the "spy" method directly doesn't work,
while passing a reference to the namespace (object) along with the
constructor function's name "foo" does. The difference in behavior
might better be explained by the author.

See linked fiddle:

http://jsfiddle.net/KXUHK/1/

Take care,

Erin

2013/2/10 Billy V. <bil...@gmail.com>:
> --
> You received this message because you are subscribed to the Google Groups
> "Sinon.JS" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to sinonjs+u...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

Christian Johansen

unread,
Feb 11, 2013, 2:53:01 AM2/11/13
to sin...@googlegroups.com
The reason you cannot pass a stand-alone function object and expect it
to be globally replaced is that Sinon won't know what reference to
replace. Even if it did, it is not possible to programatically replace
local variable bindings in JavaScript. Either use an object and
sinon.stub(object, "method"), or override the variable yourself, `foo =
sinon.spy();`.

Christian
Reply all
Reply to author
Forward
0 new messages