Skip to content Skip to sidebar Skip to footer

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. For example: it('some_test1', function(){ // something that could fail }) i

Solution 1:

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

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

Solution 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(newError('something went wrong'));
  })
})

Post a Comment for "Detecting Test Failures From Within Aftereach Hooks In Mocha"