gpt4 book ai didi

javascript - 对 Nodejs 中发出的事件进行单元测试的最佳方法是什么?

转载 作者:IT老高 更新时间:2023-10-28 22:01:56 25 4
gpt4 key购买 nike

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

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

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

最好的测试方法是什么?

最佳答案

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

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

如果您不能保证事件何时触发,那么它可能不适合进行单元测试。

关于javascript - 对 Nodejs 中发出的事件进行单元测试的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16826352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com