jasmine.Clock VS sinon.clock我的jasmin.Clock.useMock()用法有什么问题?

时间:2012-06-19 22:06:51

标签: javascript tdd coffeescript jasmine sinon

我只是尝试用jasmine在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()

1 个答案:

答案 0 :(得分:2)

如果传递的参数是函数或字符串,Jasmine只是尝试调用sinon测试的函数。如果是一个字符串,则调用eval

<强>茉莉花:

jasmine.getGlobal().setTimeout = function(funcToCall, millis) {
  if (jasmine.Clock.installed.setTimeout.apply) {
    return jasmine.Clock.installed.setTimeout.apply(this, arguments);
  } else {
    return jasmine.Clock.installed.setTimeout(funcToCall, millis);
  }
};

<强>兴农:

if (typeof timer.func == "function") {
    timer.func.apply(null, timer.invokeArgs);
} else {
    eval(timer.func);
}

所以这将通过Jasmin测试

setTimeout(fire_callback, 1000);

虽然这会失败

setTimeout("fire_callback()", 1000);