[英]node.js testing if event was emitted using sinon.js without the use of timeouts
我試圖弄清楚當異步發出的事件發出時如何使用sinon.js進行測試?
到目前為止,我正在做的是設置一個超時,在該超時中,我知道事件將被意外發出,但這很丑陋,可能會加總測試運行的總時間,我不想這樣做:
it('check that event was called', function(done) {
...
var spy = sinon.spy();
var cbSpy = sinon.spy();
obj.on('event', spy);
obj.func(cbSpy); // emits event 'event' asynchronously and calls cbSpy after it was emitted
setTimeout(function() {
sinon.assert.calledOnce(spy, 'event "event" should be emitted once');
sinon.assert.calledOnce(cbSpy, 'func() callback should be called once'); // won't work since the callback will be called only after the event has been emitted and all event listeners finished
}, 1000);
});
可以在不使用Sinon的情況下進行刺探(這里確實不需要它)。
it('check that event was called', function(done) {
var callbackCalled = false;
var eventCalled = false;
var checkIfDone() {
if (callbackCalled && eventCalled) {
done();
}
}
var callbackSpy = function () {
callbackCalled = true;
checkIfDone();
}
var eventSpy = function () {
// Spy was called.
// Add assertions for the arguments that are passed if you want.
eventCalled = true;
checkIfDone();
};
obj.on('event', eventSpy);
// emits event 'event' and invokes callback after it was emitted
obj.func(callbackSpy);
});
最好一次只測試一件事。
it('should emit `event`', function(done) {
var callback = function () {}
var eventSpy = function () {
// Spy was called.
// Add assertions for the arguments that are passed if you want.
done()
};
obj.on('event', eventSpy);
// emits event 'event' and invokes callback after it was emitted
obj.func(callback);
});
it('should invoke the callback', function(done) {
var callback = function () {
// Callback was called.
// Add assertions for the arguments that are passed if you want.
done()
}
obj.func(callback);
});
無論哪種情況,異步過程完成后都將進行測試。 我將使用第二個示例,因為這意味着您可以一次專注於一件事,並且測試代碼更加簡潔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.