我如何检查后块中是否有任何mocha测试失败?

hur*_*lad 9 javascript testing mocha.js

describe('some tests', function () {
  /*
   * Run some tests...
   */
})

after(function () {
  failures = ? // <--- what goes here?
  console.log(failures + " tests failed!")
})
Run Code Online (Sandbox Code Playgroud)

如果测试失败,我会用这个来保持chromedriver的浏览器打开,并向酱实验室报告成功或失败.

Mocha的Runner和Reporters 拥有我正在寻找的信息,stats但我不确定如何从测试文件中获取它们.

Lou*_*uis 6

快速检查代码后,我相信代码after无法访问跑步者或记者。但是,有一种方法可以在运行时获取测试状态:

describe("blah", function () {

    it("blah", function () {
        throw new Error("blah");
    });

    after(function (){
        var failed = false;
        var tests = this.test.parent.tests;
        for(var i = 0, limit = tests.length; !failed && i < limit; ++i)
            failed = tests[i].state === "failed";
        if (failed)
            console.log("FAILED");
    });
});
Run Code Online (Sandbox Code Playgroud)

看线var tests = this.test.parent.tests。我相信这this.test似乎是与after调用相关的测试对象。的值this.test.parent是与顶级关联的套件对象describe。的值this.test.parent.tests是该套件中的测试列表。所以那里的代码会遍历每个测试,并检测测试是否处于"failed"状态。

上面代码中使用的变量都没有标记为私有(通过在名称中使用前导下划线)。同时,不能保证 Mocha 的未来版本将使用完全相同的结构。

所有测试失败都是异常,所以为了捕获钩子失败,我会用检测异常的代码包装钩子。这是一个概念验证,展示了它是如何完成的(我已经将上一个示例中的一些代码移到了一个has_failed函数中):

var hook_failure = false;
function make_wrapper(f) {
    return function wrapper() {
        try {
            f.apply(this, arguments);
        }
        catch (e) {
            hook_failure = true;
            throw e;
        }
    };
}

function has_failed(it) {
    var failed = false;
    var tests = it.test.parent.tests;
    for(var i = 0, limit = tests.length; !failed && i < limit; ++i)
        failed = tests[i].state === "failed";
    return failed;
}

describe("blah", function () {

    before(make_wrapper(function () {
        throw new Error("yikes!");
    }));

    it("blah", function () {
        throw new Error("q");
    });

    after(function (){
        var failed = has_failed(this);
        if (failed)
            console.log(this.test.parent.title + " FAILED");
    });
});

after(function () {
    if (hook_failure)
        console.log("HOOK FAILURE");
});
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我使用了包装器方法after. 但是,可以只对钩子测试使用包装器。


nil*_*esh 6

我在这里找到了这个问题的答案

afterEach(function() {
  if (this.currentTest.state == 'failed') {
    // ...
  }
});
Run Code Online (Sandbox Code Playgroud)

  • OP 不询问如何在 `afterEach` 钩子中确定在它失败之前执行的测试是否成功。OP 询问如何在 `after` 钩子中确定是否在运行 `after` 钩子后的 *any* 测试失败。 (2认同)
  • 将这段代码放在“ afterEach”挂钩中,设置一个标志,然后在“ after”挂钩中检查该标志是很容易的。 (2认同)