如何终止 mocha 测试运行?

cod*_*ode 5 javascript mocha.js node.js gruntjs

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

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

如何强制终止测试运行?

是否有任何与通话完全“相反”的内容mocha.run()。类似'mocha.stopRun()'。我在文档中找不到任何关于此的内容。

Lou*_*uis 1

我还没有找到 mocha 导出的公共 API 来要求它在任意位置终止套件。不过,一旦出现测试失败,你可以mocha.bail()在打电话之前打电话要求摩卡立即停止。mocha.run()如果您希望即使没有失败也能够停止,可以采用以下方法:

<!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>
Run Code Online (Sandbox Code Playgroud)

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

如果您要使用此方法来停止您自己的测试套件,您可能需要使用“终止 Mocha”按钮运行的代码来注册您的异步操作,以便在可能的情况下尽快终止这些操作。

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