Spying on a constructor in javascript with sinon

billy picture billy · Feb 10, 2013 · Viewed 15.6k times · Source

I am trying to create a spy on a constructor, and see if it gets called -- below are my tests. I'm using sinon-chai so the syntax is valid, but both tests fail.

var foo = function(arg) {
};

var bar = function(arg) {
    var baz = new foo(arg);
};

it('foo initialized inside of this test', function() {
    var spy = sinon.spy(foo);
    new foo('test');
    expect(spy).to.be.called;
    expect(spy).to.be.calledWith('test');
});
it('foo initialized by bar()', function() {
    var spy = sinon.spy(foo);
    bar('test');
    expect(spy).to.be.called;
    expect(spy).to.be.calledWith('test');
});

Answer

billy picture billy · Feb 12, 2013

The problem is that Sinon doesn't know what reference to spy on, so the solution is to either use an object i.e. sinon.spy(namespace, 'foo') or override the reference yourself foo = sinon.spy(foo).