detecting test failures from within afterEach hooks in Mocha
Asked Answered
H

2

36

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(){ /* ... */ })
Heloise answered 12/6, 2014 at 22:7 Comment(1)
I hate to be a downer here but you should do everything you can to avoid branching test logic (Conditional Test Logic antipattern), and also avoid tests depending on the results of other tests (Interacting Tests antipattern causing Erratic Tests). These two behaviours are the bad boys of testing anti-patterns and will be a source of never-ending headaches for you and your colleagues.Coop
A
66

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

afterEach(function() {
  if (this.currentTest.state === 'failed') {
    // ...
  }
});
Abundant answered 7/8, 2014 at 2:47 Comment(6)
For more information see: github.com/mochajs/mocha/issues/797. Specifically, it seems that passed and failed are the possible options.Serene
Apparently it can also be undefined if a failure took place in one of the before or beforeEach hooks, which means it is probably wiser to write if (this.currentTest.state !== 'passed')Serene
this.currentTest is undefined (no before hooks in test)Colloid
It seems like this.currentTest is available in the afterEach hook but is not available in after.Oxley
Also, afterEach(() => {...}); will not work because arrow functions have no this.Entomologize
Also, this.currentTest.err should be set on failureFellows
S
-5

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'));
  })
})
Smearcase answered 12/6, 2014 at 22:29 Comment(2)
I saw this in a mocha.js github issue, but I would not be able to set the "this.ok" in each of the prior tests.Heloise
sorry, I see that what is wrong here. Please use the new code, ok is a variable in the test scope. this should solve the issue.Smearcase

© 2022 - 2024 — McMap. All rights reserved.