2017-10-17 67 views
0

我觉得摩卡停止运行当前测试用例断言失败后,像这样的断言后摩卡流量控制失败

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

我需要继续断言失败后做的事情,我试图用的try ... catch ,但对于没有赶上“别人”,所以如果我做

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

这将调用完成()两次,所以我要补充一个标志,

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

我觉得这很复杂,所以我想知道是否有更简单的方法来做到这一点?

回答

0

测试失败时的after钩子将仍然被调用,这样你就可以将你的测试有这样一个钩子的上下文中:

describe('suite', function() { 

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

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

}); 
+0

实际上我想在每个测试用例完成后执行它,所以我可以使用afterEach(),但“做某事”与每个测试用例都不同,所以我不认为我可以使用它。 – Keming

+0

@KemingZeng你可以嵌套'describe'块,所以你可以为每个测试创建一个,并为每个测试分别设置一个'后'钩。 – robertklep

+0

我使用另一种方式来做到这一点,但我认为在hook之后应该是一个很好的解决方案。谢谢! – Keming

0

它之所以被称为两次是因为catch正在处理异常,但finally块将始终不管断言抛出一个错误的执行。

使用return处理您的场景 - 如果一个异常被捕获它会返回一个错误完成,否则将跳过渔获物和刚刚return done()

try { 
    // test assertion 
    a.should.equal(b) 
} catch(e) { 
    // catch the error and return it 
    console.log(e) 
    return done(e) 
} 
// just return normally 
return done() 

如果您需要在if/else场景中使用它,您可以使用变量处理它。

var theError = false; 
try { 
    // test assertion 
    a.should.equal(b) 
} catch(e) { 
    // indicate we caught an error 
    console.log(e) 
    theError = e 
} 

if (theError) { 
    // there was an exception 
    done(theError) 
} else { 
    // no exceptions! 
    done() 
} 
+0

谢谢你,我想第一个会更容易些。所以摩卡没有这个东西? – Keming

+0

摩卡确实有这方面的东西 - 请看这两个例子:)它只是一个类似于其他任何东西的库,你仍然必须在其周围编写JavaScript。 – doublesharp

+0

我的意思是我的两个例子都是有效的,但是根据具体情况,每个例子都可能更合适。您需要针对您的特定需求进行设计。 – doublesharp

0

记住finally会被执行,要么是失败,要么是不会失败。这就是为什么它执行两次。

You can do: 

    try { 
     a.should.equal(b) 
    } catch(e) { 
     console.log(e) 
     done(e) 
    } 
    done() 

如果失败,您将通过catch退出,否则继续正常返回。