2016-05-14 7 views
0

非同期で発行されたイベントが放出されたときにsinon.jsを使ってどのようにテストできますか?node.jsタイムアウトを使用せずに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); 
}); 

答えて

0

シノンを使用しないでこれで刺すようになります(本当に必要ありません)。

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); 
}); 

何が良いかは、一度に1つのことをテストすることです。

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); 
}); 

いずれの場合も、非同期プロセスが終了するとテストが実行されます。 2つ目の例を使用します。これは、一度に1つのことに集中でき、テストコードがはるかにクリーンであることを意味します。

関連する問題