【问题标题】:node.js testing if event was emitted using sinon.js without the use of timeoutsnode.js 测试是否使用 sinon.js 发出事件而不使用超时
【发布时间】:2016-05-14 22:32:48
【问题描述】:

我试图弄清楚当异步发出的事件已经发出时如何使用 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);
});

【问题讨论】:

    标签: javascript node.js unit-testing mocha.js sinon


    【解决方案1】:

    打算尝试一下,但不使用诗乃(这里真的不需要)。

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

    在任何一种情况下,测试都将在异步进程完成后完成。我会使用第二个示例,因为这意味着您可以一次只专注于一件事,并且测试代码更加简洁。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-14
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 1970-01-01
      • 2012-05-22
      相关资源
      最近更新 更多