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

标签 node.js mocha.js

当我使用 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/

相关文章:

javascript - Mocha 测试使用 superagent + promises 超时而不是失败并返回 'expect'

node.js - mocha 在测试完成后挂起

node.js - 有没有办法根据 package.json 的更改来更新特定的依赖项?

node.js - 如何使用 Express 服务器/ react 客户端在另一个域中 SSO 并重定向到另一个域?

javascript - Istanbul 尔给了我报道但以错误结束输出

javascript - 使用 node.js、Mocha 和 mocha-jsdom 测试 Typescript 生成的类?

javascript - `Firebase` 包被成功找到。但是,这个包本身指定了一个无法解析的 `main` 模块字段

node.js - 使用 mongoose 返回包含某个字段的所有文档

node.js - 通过多次调用计算异步函数的执行时间

mongodb - Mongoose 和独特的领域