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'); });
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.
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 .
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").
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With