32

我正在编写一堆 mocha 测试,我想测试是否发出了特定事件。目前,我正在这样做:

  it('should emit an some_event', function(done){
    myObj.on('some_event',function(){
      assert(true);
      done();
    });
  });

但是,如果该事件从未发出,它会使测试套件崩溃,而不是使该测试失败。

测试这个的最佳方法是什么?

4

8 回答 8

37

If you can guarantee that the event should fire within a certain amount of time, then simply set a timeout.

it('should emit an some_event', function(done){
  this.timeout(1000); //timeout with an error if done() isn't called within one second

  myObj.on('some_event',function(){
    // perform any other assertions you want here
    done();
  });

  // execute some code which should trigger 'some_event' on myObj
});

If you can't guarantee when the event will fire, then it might not be a good candidate for unit testing.

于 2013-05-30T07:20:09.970 回答
17

9月30日编辑:

我看到我的答案被接受为正确答案,但 Bret Copeland 的技术(见下面的答案)更好,因为它在测试成功时更快,这将是大多数情况下作为测试套件的一部分运行测试的情况.


Bret Copeland 的技术是正确的。你也可以做一些不同的事情:

  it('should emit an some_event', function(done){
    var eventFired = false
    setTimeout(function () {
      assert(eventFired, 'Event did not fire in 1000 ms.');
      done();
    }, 1000); //timeout with an error in one second
    myObj.on('some_event',function(){
      eventFired = true
    });
    // do something that should trigger the event
  });

这可以在Sinon.js的帮助下缩短一点。

  it('should emit an some_event', function(done){
    var eventSpy = sinon.spy()
    setTimeout(function () {
      assert(eventSpy.called, 'Event did not fire in 1000ms.');
      assert(eventSpy.calledOnce, 'Event fired more than once');
      done();
    }, 1000); //timeout with an error in one second
    myObj.on('some_event',eventSpy);
    // do something that should trigger the event
  });

在这里,我们不仅要检查是否触发了事件,还要检查是否在超时期间仅触发了一次 if 事件。

Sinon 还支持calledWithandcalledOn来检查使用了哪些参数和函数上下文。

请注意,如果您希望事件与触发事件的操作同步触发(中间没有异步调用),那么您可以将超时设置为零。1000 ms 的超时仅在您执行异步调用时才需要,这需要很长时间才能完成。很可能不是这样。

实际上,当事件保证与导致它的操作同步触发时,您可以将代码简化为

  it('should emit an some_event', function() {
    eventSpy = sinon.spy()
    myObj.on('some_event',eventSpy);
    // do something that should trigger the event
    assert(eventSpy.called, 'Event did not fire.');
    assert(eventSpy.calledOnce, 'Event fired more than once');
  });

否则,Bret Copeland 的技术在“成功”情况下(希望是常见情况)总是更快,因为它能够done在事件被触发时立即调用。

于 2013-05-30T09:06:45.690 回答
7

这种方法确保了最短的等待时间,但套件超时设置的最大机会,并且非常干净。

  it('should emit an some_event', function(done){
    myObj.on('some_event', done);
  });

也可以将它用于 CPS 风格的功能......

  it('should call back when done', function(done){
    myAsyncFunction(options, done);
  });

这个想法也可以扩展到检查更多细节 - 例如参数和this- 通过放置一个包装器 arround done。例如,多亏了这个答案,我可以做...

it('asynchronously emits finish after logging is complete', function(done){
    const EE = require('events');
    const testEmitter = new EE();

    var cb = sinon.spy(completed);

    process.nextTick(() => testEmitter.emit('finish'));

    testEmitter.on('finish', cb.bind(null));

    process.nextTick(() => testEmitter.emit('finish'));

    function completed() {

        if(cb.callCount < 2)
            return;

        expect(cb).to.have.been.calledTwice;
        expect(cb).to.have.been.calledOn(null);
        expect(cb).to.have.been.calledWithExactly();

        done()
    }

});
于 2016-08-10T10:34:41.117 回答
3

坚持:

this.timeout(<time ms>);

在您的 it 声明的顶部:

it('should emit an some_event', function(done){
    this.timeout(1000);
    myObj.on('some_event',function(){
      assert(true);
      done();
    });`enter code here`
  });
于 2014-06-19T16:06:54.503 回答
2

在这里聚会迟到了,但我正面临这个问题,并想出了另一个解决方案。Bret 接受的答案是一个很好的答案,但我发现它在运行我的完整 mocha 测试套件时造成了严重破坏,抛出了错误done() called multiple times,我最终放弃了尝试进行故障排除。Meryl 的回答让我走上了我自己的解决方案的道路,该解决方案也使用sinon,但不需要使用超时。通过简单地存根emit()方法,您可以测试它是否被调用并验证它的参数。这假设您的对象继承自 Node 的 EventEmitter 类。在您的情况下,方法的名称emit可能会有所不同。

var sinon = require('sinon');

// ...

describe("#someMethod", function(){
    it("should emit `some_event`", function(done){
        var myObj = new MyObj({/* some params */})

        // This assumes your object inherits from Node's EventEmitter
        // The name of your `emit` method may be different, eg `trigger`  
        var eventStub = sinon.stub(myObj, 'emit')

        myObj.someMethod();
        eventStub.calledWith("some_event").should.eql(true);
        eventStub.restore();
        done();
    })
})
于 2015-03-14T19:13:47.720 回答
0

我建议使用once()更简单的解决方案,特别是如果您喜欢 async/await 风格:

const once = require('events').once
// OR import { once } from 'events'

it('should emit an some_event', async function() {
    this.timeout(1000); //timeout with an error if await waits more than 1 sec

    p = once(myObj, 'some_event')
    // execute some code which should trigger 'some_event' on myObj
    await p
});

如果您需要检查值:

[obj] = await p
assert.equal(obj.a, 'a')

最后,如果您使用的是打字稿,以下帮助程序可能会很方便:

// Wait for event and return first data item
async function onceTyped<T>(event: string): Promise<T> {
    return <T>(await once(myObj, event))[0]
}

像这样使用:

 const p = onceTyped<SomeEvent>(myObj, 'some_event')
 // execute some code which should trigger 'some_event' on myObj
 const someEvent = await p // someEvent has type SomeEvent
 assert.equal(someEvent.a, 'a')
于 2021-12-06T09:42:30.433 回答
0

代替 sinon.timers更好的解决方案是使用es6 - Promises

//Simple EventEmitter
let emitEvent = ( eventType, callback ) => callback( eventType )

//Test case
it('Try to test ASYNC event emitter', () => {
  let mySpy = sinon.spy() //callback
  return expect( new Promise( resolve => {
    //event happends in 300 ms
    setTimeout( () => { emitEvent('Event is fired!', (...args) => resolve( mySpy(...args) )) }, 300 ) //call wrapped callback
  } )
  .then( () => mySpy.args )).to.eventually.be.deep.equal([['Event is fired!']]) //ok
})

如您所见,关键是用 resolve: (... args) => resolve (mySpy (... args))包装回调。

因此,PROMIS new Promise().then()只有在被调用回调之后才会被解析。

但是一旦回调被调用,你就可以测试你对他的期望。

优点

  • 我们不需要猜测超时等待事件被触发(在许多 describe() 和 its() 的情况下),不取决于计算机的性能
  • 并且测试会更快通过
于 2016-11-07T02:11:15.163 回答
0

I do it by wrapping the event in a Promise:

// this function is declared outside all my tests, as a helper
const waitForEvent = (asynFunc) => {
    return new Promise((resolve, reject) => {
        asyncFunc.on('completed', (result) => {
            resolve(result);
        }
        asyncFunc.on('error', (err) => {
            reject(err);
        }
    });
});

it('should do something', async function() {
    this.timeout(10000);  // in case of long running process
    try {
        const val = someAsyncFunc();
        await waitForEvent(someAsyncFunc);
        assert.ok(val)
    } catch (e) {
        throw e;
    }
}
于 2019-08-22T01:48:10.737 回答