简体   繁体   English

从Mocha中的afterEach挂钩中检测测试失败

[英]detecting test failures from within afterEach hooks in Mocha

I'm trying to create an afterEach hook with logic that should only fire if the previous test failed. 我正在尝试创建一个带有逻辑的afterEach挂钩,只有在前一次测试失败时才会触发。 For example: 例如:

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
  }
})

However, I have no known way of detecting if a test failed from within the afterEach hook. 但是,我没有办法在afterEach钩子中检测测试是否失败。 Is there some sort of event listener I can attach to mocha? 是否有某种事件监听器我可以附加到摩卡? Maybe something like this: 也许是这样的:

myTests.on("error", function(){ /* ... */ })

You can use this.currentTest.state (not sure when this was introduced): 你可以使用this.currentTest.state (不确定何时引入):

afterEach(function() {
  if (this.currentTest.state === 'failed') {
    // ...
  }
});

You can do like the following 您可以执行以下操作

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'));
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM