gpt4 book ai didi

node.js - Mocha 怎么知道只有我的异步测试才能等待和超时?

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

当我使用 Mocha 进行测试时,我经常需要同时运行异步和同步测试。

Mocha 很好地处理了这个问题,让我可以在我的测试异步时指定回调,done

我的问题是,Mocha 如何在内部观察我的测试并知道它应该等待异步事件?只要我在测试函数中定义了回调参数,它似乎就在等待。您可以在下面的示例中看到,第一个测试应该超时,第二个应该在 user.save 调用匿名函数之前继续并完成。

// In an async test that doesn't call done, mocha will timeout.
describe('User', function(){
describe('#save()', function(){
it('should save without error', function(done){
var user = new User('Luna');
user.save(function(err){
if (err) throw err;
});
})
})
})

// The same test without done will proceed without timing out.
describe('User', function(){
describe('#save()', function(){
it('should save without error', function(){
var user = new User('Luna');
user.save(function(err){
if (err) throw err;
});
})
})
})

这是 node.js 特有的魔法吗?这是可以在任何 Javascript 中完成的事情吗?

最佳答案

这是简单的纯 Javascript 魔法。

函数其实就是对象,它们都有属性(比如函数定义的参数个数)。

看看mocha/lib/runnable.js中this.async是怎么设置的

function Runnable(title, fn) {
this.title = title;
this.fn = fn;
this.async = fn && fn.length;
this.sync = ! this.async;
this._timeout = 2000;
this._slow = 75;
this.timedOut = false;
}

Mocha 的逻辑会根据你的函数是否用参数定义而改变。

关于node.js - Mocha 怎么知道只有我的异步测试才能等待和超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13570485/

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