【问题标题】:mocha global `before` that executes only 1 timemocha global `before` 只执行 1 次
【发布时间】:2017-12-24 07:52:02
【问题描述】:

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

我的测试中有几个文件。

如何在所有测试开始前只运行一段代码?

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

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

【问题讨论】:

  • 到目前为止我发现的最简单的方法是创建一个名称以下划线开头的文件,例如_before.test.js 将在其他测试之前运行,因为 mocha 按字母顺序加载它们。

标签: javascript node.js mocha.js functional-testing


【解决方案1】:

如果您将它们放在任何描述块之外,您可以拥有“根”级别的挂钩。因此,您可以将相关代码放在 test 文件夹内的任何文件中。

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

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

【讨论】:

    【解决方案2】:

    Mocha 8 引入了root hook plugins 的概念。在您的情况下,相关的是 beforeAll 和 afterAll,它们将在所有测试之前/之后运行一次,只要您的测试是串行运行的。

    你可以写:

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

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

    请参阅docs 了解更多信息。

    【讨论】:

      【解决方案3】:

      对此有一个非常干净的解决方案。在 mocha 命令中使用 --file 作为参数。对于您的测试,它就像一个全局挂钩。

      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 的方法。所以我认为你可能不得不满足于使用“旧”的承诺和回调代码。

      【讨论】:

        猜你喜欢
        • 2017-02-05
        • 2019-10-14
        • 2017-07-27
        • 1970-01-01
        • 1970-01-01
        • 2016-08-13
        • 2021-10-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多