心跳监视器并在 JavaScript 中对其进行单元测试 - 如何?
我有一个“服务模块”,它监听周期性的心跳(通过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() 函数之外。
I have a 'service module' that listens for periodic heartbeats (over socket.io) and then if a heartbeat is missed publishes an event on an event bus (Backbone.Events). Also if the heart beat resumes later, it publishes an event.
My unit test looks something like this:
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
});
My dislike for this test is that if it fails then it is likely that the reporting tool will list the failures under a different test - since the actual assertion will occur outside the it() function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用SinonJSs fake计时器将时钟向前设置2个刻度,而不是使用setTimeout。
You could use SinonJSs fake timer to set the clock 2 ticks forward instead of using setTimeout.