您还可以将测试包装到一个套件中,在根套件中您可以初始化必要的东西,例如数据库连接等。然后,您可以使用全局变量 https://stackabuse.com/using-global-variables-in-node-js/.
测试套件 1 (suite1.test.js):
describe("Root of Suite 1", function () {
describe("Function of Suite 1", function () {
it("should do ..", async function () {
...
});
});
});
测试套件 2 (suite2.test.js):
describe("Root of Suite 2", function () {
// This will inform root suite about the completion of tests
after(function () {
global.isTestsCompleted = true;
});
describe("Function of Suite 2", function () {
it("should do ..", async function () {
...
});
});
});
根套件(root.test.js):
const { isReady } = require("../db");
describe("Root Suite", function () {
this.timeout(60000);
// Wait until the DB connection is ready
before(function (done) {
isReady().then(() => done());
global.isTestsCompleted = false;
});
// Check the variable every 500ms to see if all test suites executed
after(function () {
setInterval(() => {
if (global.isTestsCompleted) {
process.exit(1);
}
}, 500);
});
require("./suite1.test.js");
require("./suite2.test.js");
});
在上面,套件的顺序要求很重要。它们将按照我们导入它们的顺序执行。因此,我们将控制机制放在最后一个套件中,即suite2.test.js
.
Update还有一个内部选项可以在所有测试运行后终止 mocha 进程:mocha --exit
。
因此,在这种情况下我们不需要使用全局变量,根套件如下所示:
const { isReady } = require("../db");
describe("Root Suite", function () {
this.timeout(60000);
// Wait until the DB connection is ready
before(function (done) {
isReady().then(() => done());
});
require("./suite1.test.js");
require("./suite2.test.js");
});