Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spying on a constructor in javascript with sinon

Tags:

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'); }); 
like image 807
billy Avatar asked Feb 10 '13 17:02

billy


People also ask

What does Sinon spy do?

The function sinon. spy returns a Spy object, which can be called like a function, but also contains properties with information on any calls made to it. In the example above, the firstCall property has information about the first call, such as firstCall. args which is the list of arguments passed.

What does Sinon spy return?

spy. Returns true if spy was called at least once with the provided arguments. Can be used for partial matching, Sinon only checks the provided arguments against actual arguments, so a call that received the provided arguments (in the same spots) and possibly others as well will return true .

How do you stub the instance of a class in Sinon?

to stub the myMethod instance method in the YourClass class. We call callsFake with a callback that returns the value we want for the fake method. sinon. stub(YourClass, "myStaticMethod").

What is Spy in JavaScript?

Spies allow you to monitor a function; they expose options to track invocation counts, arguments and return values. This enables you to write tests to verify function behaviour. They can even help you mock out unneeded functions. For example, dummy spies can be used to swap out AJAX calls with preset promise values.


Video Answer


1 Answers

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).

like image 89
billy Avatar answered Oct 04 '22 03:10

billy