测试同步代码

Kon*_*nel 6 mocha.js node.js

我有一段使用node-sync的代码,如下所示:

function funcA() {
  return new Promise(function(resolve, reject) {
    Sync(function () {
      return funcB.sync();
    }, function (err, result) {
      if(err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
}
Run Code Online (Sandbox Code Playgroud)

此代码使用mocha + chai进行测试:

it("should return array", function() {
  return funcA().then(function(result) {
    expect(result).to.be.an.instanceof(Array);
  });
});
Run Code Online (Sandbox Code Playgroud)

几个月前它工作得很好,但现在这个测试总是超时:

错误:超过2000毫秒的超时.确保在此测试中调用done()回调.

到目前为止我尝试过的:

  • 使用done()而不是返回一个承诺
  • 替换node-syncsynchronize.js
  • 增加超时

我发现的是,expect(...这个测试的一部分实际上是被调用的,但只有在摩卡杀死测试之后.无论当前设置的expect(..是什么超时间隔,都会在收到Error: timeout消息后约20毫秒被调用.

我通过setInterval(function(){}, 10)在测试文件的顶部添加来解决问题.我想知道为什么这有效,如果有更好的方法来解决这个问题?

[编辑]看起来这是一个特定于节点版本的问题.测试在0.12.4上失败,但在0.10.38上正确运行.

[编辑]实际代码可在此处获得.

bea*_*der 1

您可能只是错过了done()回调:

it("should return array", function(done) {
    funcA().then(function(result) {
        expect(result).to.be.an.instanceof(Array);
        done();
    });
});
Run Code Online (Sandbox Code Playgroud)

http://mochajs.org/#asynchronous-code