只执行 1 次的 mocha global `before`

mocha global `before` that executes only 1 time

我正在使用 mocha 进行 node.js 功能测试。

我的测试中有几个文件。

我怎样才能 运行 一段代码在所有测试开始前只用一次?

例如,我可能必须在所有测试开始之前设置一个 docker 容器。 可以用 mocha 做到这一点吗?

before hook 运行s 每个测试文件 1 次。这不符合我的需求。

你可以有 'root' 级钩子,如果你把它们放在任何描述块之外。所以你可以把你的相关代码放在测试文件夹内的任何文件中。

before(function() {
  console.log('before any tests started');
});

查看文档:http://mochajs.org/#root-level-hooks

有一个非常干净的解决方案。在您的 mocha 命令中使用 --file 作为参数。它就像一个 global hook 用于测试。

xargs mocha -R spec --file <path-to-setup-file>

安装文件可能如下所示:

'use strict';
const mongoHelper = require('./mongoHelper.js');

console.log("[INFO]: Starting tests ...");
// connect to database

mongoHelper.connect()
.then(function(connection){
  console.log("[INFO]: Connected to database ...");
  console.log(connection);
})
.catch(function(err){
  console.error("[WARN]: Connection to database failed ...");
  console.log(err);
});

不幸的是,我还没有找到在这个安装文件中使用 async/await 的方法。所以我认为您可能必须满足于使用 "old" 承诺和回调代码。

Mocha 8 引入了root hook plugins 的概念。在您的情况下,相关的是 beforeAllafterAll,这将 运行 一次 before/after 所有测试,只要您连续测试 运行。

你可以这样写:

exports.mochaHooks = {
  beforeAll(done) {
    // do something before all tests run
    done();
  },
};

并且您必须使用 --require 标志添加此文件。

有关详细信息,请参阅 docs