Using Sinon.js
Adds a new
context
block.Will use sinon spies. This lets him to observe when and how a method was called.
Sometimes you don’t want side effects. For example the
listenTo
events. We don’t want them to fire. We want to stub the
listenTo
method.We need to set up stubs before they are called. Here we want to test the initialise method.
..
context('creates dependencies', function(){
..
});
context('attaches event handlers', function(){
before(function(){
// the next time listenTo is called, it will be stubbed
this.stub = sinon.stub(App.prototype, 'listenTo');
this.app = new App();
});
// we need to release the stub
after(function(){
this.stub.restore();
});
it('listens to collection "add"', function(){
assert.ok( this.stub.calledWith( this.app.collection, 'add', this.app.renderComment ));
});
});
..
Then does the same with the other listenTo
methods (add remove
, sync
).Then tests that “it calls collection
.fetch
It’s more complicated. We need to add the collection object and spy on it. Spy lets the call fall through.
..
it('calls collection .fetch', function(){
var spy = sinon.spy(CommentsCollection.prototype.fetch);
var app = new App();
assert.ok(spy.called);
spy.restore();
})