对Nodejs中发出的事件进行单元测试的最佳方法是什么? [英] What's the best way to unit test an event being emitted in Nodejs?

查看:59
本文介绍了对Nodejs中发出的事件进行单元测试的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写大量的摩卡测试,我想测试特定事件的发出.目前,我正在这样做:

I'm writing a bunch of mocha tests and I'd like to test that particular events are emitted. Currently, I'm doing this:

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

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

However, if the event never emits, it crashes the test suite rather than failing that one test.

最好的测试方法是什么?

What's the best way to test this?

推荐答案

如果可以保证事件应在一定时间内触发,则只需设置一个超时时间即可.

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.

这篇关于对Nodejs中发出的事件进行单元测试的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆