我只是尝试用茉莉花在 javascript/coffeescript 中进行单元测试,非常好。
我一直在尝试使用 jasmine.Clock.Mock() 及时推进并触发 setTimeout 回调。
唉 jasmine.Clock.tick(1001) 似乎没有任何效果!然后我发现 sinon.js 有自己的时间模拟,使用这个就可以了。我想了解为什么。
这是一个要测试的虚拟 jquery 插件:
dummy_method = function(callback) {
fire_callback = function() {
callback();
}
setTimeout("fire_callback()", 1000);
}
这是规格的两个版本:
# 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()