断言失败后的Mocha流控制 [英] Mocha flow control after assertion fails

查看:113
本文介绍了断言失败后的Mocha流控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为mocha会在断言失败后停止运行当前的测试用例,像这样

I think mocha stops running the current test case after assertion fails, like this

it('test', function(done) {
    a.should.equal(b);
    //if a is not equal to be, won't go here
    //do something
    done();
}

断言失败后,我需要继续做某件事,我尝试使用try ... catch,但是没有"else"来捕获,所以如果我这样做

I need to continue doing something after assertion fails, I tried to use try...catch, but there is no "else" for catch, so if I do

try {
    a.should.equal(b)
} catch(e) {
    console.log(e)
    done(e)
} finally {
    //do something
    done()
}

这将调用done()两次,所以我必须添加一个标志,

this will call done() twice, so I have to add a flag,

var flag = true;
try {
    a.should.equal(b)
} catch(e) {
    console.log(e)
    flag = false
    done(e)
} finally {
    //do something
    if(flag)
        done()
}

我认为这是如此复杂,所以我想知道是否有更简单的方法?

I think this is so complicated, so I wonder if there is an easier way to do it?

推荐答案

当测试失败时,仍会调用after挂钩,因此您可以将测试放在具有此类挂钩的上下文中:

An after hook will still get called when a test fails, so you can place your test inside a context that has such a hook:

describe('suite', function() {

  after(function(done) {
    // do something
    done();
  });

  it('test', function(done) {
    a.should.equal(b);
    done();
  }

});

这篇关于断言失败后的Mocha流控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆