我有一个"服务模块",它侦听周期性的心跳(通过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()函数之外。
您可以使用SinonJS的假计时器将时钟向前设置2次,而不是使用setTimeout。