如何继续运行已失败的摩卡`it`?

时间:2015-12-18 02:15:10

标签: mocha

以下mocha it声明:

it('should do truthy and falsey things', function() {
    var val = true;
    assert.equal(val, true, "true should be true!");
    console.log('state 1:', val);
    val != val;
    assert.equal(true, false, "should continue running even after failing");
    console.log('state 2:', val);
    val != val;
    assert.equal(false, false, "false should be false!");
});

会产生以下日志:

state 1: true
    1) should do truthy and falsey things

就是这样。一旦第二个断言失败,该函数的其余部分就不会运行。

是否可以使用函数的其余部分(在本例中为最后三行),如果是,如何

1 个答案:

答案 0 :(得分:2)

防止断言失败结束测试的最直接方法是捕获失败引发的异常并稍后重新抛出。但是,我不建议这样做,因为这会产生复杂性。如果多个测试失败,您将重新抛出哪个例外?此外,您必须记住以重新抛出您捕获的异常,否则测试似乎正在通过。

一般来说,我只是接受这样一个事实:如果我有多个断言的测试,那么测试将在第一次失败时停止。在我无法忍受的情况下,我通常采用一种策略,即将检查记录到结构中,然后将结构与测试结束时的预期值进行比较。构造结构的方法有很多种。这是一个例子:

it('should allow multiple tests', function () {
    var expected = {
        "something should be true": true,
        "something should be false": false,
        "forgot this one": 1
    };

    var actual = {};

    var thing_to_test = true;

    // First test
    actual["something should be true"] = thing_to_test;

    // Second test
    actual["something should be false"] = thing_to_test;

    // We forget the third test.

    assert.equal(actual, expected);
});

当我运行上面的测试时,我得到以下输出:

  1) should allow multiple tests

  0 passing (12ms)
  1 failing

  1)  should allow multiple tests:

      AssertionError: { 'something should be true': true,
  'something should be false': true } == { 'something should be true': true,
  'something should be false': false,
  'forgot this one': 1 }
      + expected - actual

       {
      -  "something should be false": true
      +  "forgot this one": 1
      +  "something should be false": false
         "something should be true": true
       }

      at Context.<anonymous> (test.js:22:12)