1

我有一个“服务模块”,它侦听周期性的心跳(通过 socket.io),然后如果错过了心跳,则会在事件总线(Backbone.Events)上发布一个事件。此外,如果心跳稍后恢复,它会发布一个事件。

我的单元测试看起来像这样:

describe('Heartbeat service', function() {
  var HeartbeatService;
  var heartbeatInterval = 1;
  //the server is expected to send heartbeats FASTER actually.
  //otherwise we risk false alarms

  jasmine.require(['services/HeartbeatService'], function(Service) {
    HeartbeatService = Service;
  });

  /*Since these tests use setInterval, it'd be erroneous to allow
    mocks to be overwritten by another test. Thus not using beforeEach()*/
  function createMocks(){
    var mockEventAggregator = jasmine.createSpyObj('Events',['trigger']);
    return {
      target : new HeartbeatService(heartbeatInterval, mockEventAggregator),
      ea     : mockEventAggregator
    };
  }

  it('should raise an event on the FIRST missed beat', function() {
    var mocks = createMocks();
    mocks.target.start();
    setTimeout(function(){
      expect(mocks.ea.trigger).toHaveBeenCalled();
    }, 2);
  });
  //..other similar tests
});

我不喜欢这个测试,如果它失败了,那么报告工具很可能会在不同的测试下列出失败——因为实际的断言将发生在 it() 函数之外。

4

1 回答 1

1

您可以使用SinonJS 的假计时器将时钟设置为 2 滴答,而不是使用 setTimeout。

于 2012-02-26T20:40:49.910 回答