【问题标题】:How to terminate mocha test runs?如何终止摩卡测试运行?
【发布时间】:2013-11-27 06:42:13
【问题描述】:

我想在执行一堆测试用例时终止所有其余的测试用例。

我正在使用 mocha 在 ui 界面(在浏览器上)。

如何强制终止测试运行?

电话mocha.run() 有什么完全“相反”的地方吗?类似“mocha.stopRun()”的东西。我在文档中找不到与此相关的任何内容。

【问题讨论】:

  • 您是从命令行还是在浏览器中运行 mocha?
  • 我在 Mocha 资源中找不到任何表明这是可能的:(

标签: javascript node.js gruntjs mocha.js


【解决方案1】:

我没有找到 mocha 导出的公共 API 来要求它在任意位置终止套件。但是,您可以在调用mocha.run() 之前调用mocha.bail() 要求mocha 在测试失败时立即停止。如果您希望即使没有失败也能停止,这里有一个方法:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8"/>
    <link href="node_modules/mocha/mocha.css" type="text/css" media="screen" rel="stylesheet" />
    <script type="text/javascript" src="node_modules/mocha/mocha.js"></script>
  </head>
  <body>
    <button id="terminate">Terminate Mocha</button>
    <div id="mocha"></div>
    <script>
      var terminate = document.querySelector("#terminate");
      var runner;
      var terminated = false;
      terminate.addEventListener("click", function () {
          if (runner) {
              // This tells the test suite to bail as soon as possible.
              runner.suite.bail(true);
              // Simulate an uncaught exception.
              runner.uncaught(Error("FORCED TERMINATION"));
              terminated = true;
          }
          return false;
      });

      mocha.setup("bdd");
      describe("test", function () {
          this.timeout(5 * 1000);
          it("first", function (done) {
              console.log("first: do nothing");
              done();
          });
          it("second", function (done) {
              console.log("second is executing");
              setTimeout(function () {
                  // Don't call done() if we forcibly terminated mocha.
                  // If we called done() no matter what, then if we terminated
                  // the run while this test is running, mocha would mark it
                  // as failed, and succeeded!
                  if (!terminated)
                      done();
              }, 2.5 * 1000);
          });
          it("third", function (done) {
              console.log("third: do nothing");
              done();
          });
      });
      runner = mocha.run();
    </script>
  </body>
</html>

如果在 mocha 忙于第二次测试时单击“终止 Mocha”按钮,将导致第二次测试失败,第三次测试将无法执行。您可以通过查看控制台中的输出来验证这一点。

如果您想以此作为停止您自己的测试套件的方法,您可能希望使用“终止 Mocha”按钮运行的代码注册您的异步操作,以便尽快终止这些操作,如果完全有可能。

请注意,runner.suite.bail(true) 不是公共 API 的一部分。我一开始尝试调用mocha.bail(),但在测试运行过程中调用它不起作用。 (只有在调用 mocha.run() 之前调用它才会起作用。)runner.uncaught(...) 也是私有的。

【讨论】:

【解决方案2】:

你会想要找到 mocha 进程,然后使用 Node 的process.kill

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多