1
我有一個'服務模塊',用於偵聽週期性心跳(通過socket.io),然後如果心跳錯過,則在事件總線(Backbone.Events)上發佈事件。如果心跳稍後恢復,它會發佈一個事件。心跳監視器和單元測試它在JavaScript - 如何?
我的單元測試看起來是這樣的:
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()函數外發生。
我希望你不是通過javascript監測真正的患者;) – mpm 2012-02-24 18:45:28