detecting test failures from within afterEach hooks in Mocha

拟墨画扇 提交于 2019-12-30 02:36:09

问题


I'm trying to create an afterEach hook with logic that should only fire if the previous test failed. 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. Is there some sort of event listener I can attach to mocha? Maybe something like this:

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

回答1:


You can use this.currentTest.state (not sure when this was introduced):

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



回答2:


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


来源:https://stackoverflow.com/questions/24194672/detecting-test-failures-from-within-aftereach-hooks-in-mocha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!