Mocha before 在 It 块之后执行

Mocha before executes after It block

我正在尝试使用 mocha 和 chai 为 node.js 做单元测试用例。

index.js

module.exports = {
    setA: function () {
        return new Promise(function () {
            setTimeout(function () {
                console.log("aaaa");
                a = 1;
            }, 2000)

        })
    }
}

index.spec.js

var assert = require("assert");
var SetA = require("./index")
a = 0;
before(function() {
  SetA.setA();

});
it('a should be set to 1', function() {
  assert(a === 1);
});
index.js 文件中的 SetA 方法返回一个承诺。 before 块不等待完成。 2000 毫秒后只有 before 块是 completed.so 我的测试用例失败了。摩卡版本是5.2.0

测试用例

如何使before块同步,使其在执行完成后才移动到It块?

Mocha 理解 promise,因此您应该能够 return SetA:

生成的 promise
before(function() {
  return SetA.setA(); 
});

同时查看您的函数 SetA - 您永远不会兑现该承诺。你需要这样的东西:

module.exports = {
    setA: function () {
        return new Promise(function (resolve) { //<< resolve
            setTimeout(function () {
                console.log("aaaa");
                a = 1;
                resolve() //<< call resolve when you're done
            }, 2000)

        })
    }
}