Javascript 从摩卡每个挂钩内检测测试失败
我正在尝试创建一个带有逻辑的afterEach钩子,该钩子只有在上一次测试失败时才会触发。例如:Javascript 从摩卡每个挂钩内检测测试失败,javascript,node.js,mocha.js,Javascript,Node.js,Mocha.js,我正在尝试创建一个带有逻辑的afterEach钩子,该钩子只有在上一次测试失败时才会触发。例如: it("some_test1", function(){ // something that could fail }) it("some_test2", function(){ // something that could fail }) afterEach(function(){ if (some_test_failed) { // do something to re
it("some_test1", function(){
// something that could fail
})
it("some_test2", function(){
// something that could fail
})
afterEach(function(){
if (some_test_failed) {
// do something to respond to the failing test
} else {
// do nothing and continue to next test
}
})
但是,我没有已知的方法来检测每个挂钩内的测试是否失败。是否有某种类型的事件监听器可以连接到摩卡?也许是这样的:
myTests.on("error", function(){ /* ... */ })
你可以这样做
describe('something', function(){
var ok = true;
it('should one', function(){
ok = true;
})
it('should two', function(){
// say the test fails here
ok = false;
})
afterEach(function(){
if (!ok) this.test.error(new Error('something went wrong'));
})
})
您可以使用
this.currentTest.state
(不确定何时引入此选项):
我在中看到了这一点,但我无法在之前的每个测试中设置“this.ok”。对不起,我看到这里出了问题。请使用新代码,
ok
是测试范围内的变量。这应该能解决问题。这正是我想要的。谢谢有关详细信息,请参阅:。具体地说,似乎通过
和失败
是可能的选项。显然,如果每个钩子之前的或之前的钩子中有一个发生了故障,那么它也可能是未定义的
,这意味着编写if(this.currentTest.state!=“passed”)可能更明智
看起来像是这个。currentTest
在afterEach
钩子中可用,但在after
中不可用。另外,afterEach(()=>{…})
将不起作用,因为arrow函数没有这个
。我不想在这里让人沮丧,但您应该尽一切努力避免分支测试逻辑(条件测试逻辑反模式),也应该避免依赖于其他测试结果的测试(交互测试反模式导致不稳定测试)。这两种行为都是测试反模式的坏孩子,对你和你的同事来说将是永无止境的头痛之源。
afterEach(function() {
if (this.currentTest.state === 'failed') {
// ...
}
});