I’m just giving a try to unit testing in javascript/coffeescript with jasmine, very nice.
I’ve been trying to use jasmine.Clock.Mock() to advance in time and fire setTimeout callbacks.
Alas the jasmine.Clock.tick(1001) did not seem to have any effect !
I then discovered sinon.js that had its own time mock, and using this one it was allright. I’d like to understand why.
Here is a dummy jquery plugin to be tested:
dummy_method = function(callback) {
fire_callback = function() {
callback();
}
setTimeout("fire_callback()", 1000);
}
And here are both versions of the specs :
# Working test (spy was called as expected), using sinon FakeTimers
describe "jQuery.fn.countdown", ->
beforeEach () ->
this.clock = sinon.useFakeTimers();
afterEach () ->
this.clock.restore()
it 'should fireup the callback', ->
countdown_callback = jasmine.createSpy('countdown_callback');
dummy_method(countdown_callback)
this.clock.tick(1001)
expect(countdown_callback).toHaveBeenCalled()
# Non-working test (spy is never called), using jasmine Clock Mock
describe "jQuery.fn.countdown", ->
beforeEach () ->
jasmine.Clock.useMock()
it 'should fireup the callback', ->
countdown_callback = jasmine.createSpy('countdown_callback');
dummy_method(countdown_callback)
jasmine.Clock.tick(1001)
expect(countdown_callback).toHaveBeenCalled()
Jasmine just try to call a function where sinon test if the passed argument is a function or a string. If its a string it call
eval.Jasmine:
Sinon:
So this will pass the Jasmin test
while this will fail