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(){ /* ... */ })
omdel
  • 911
  • 1
  • 9
  • 13
  • 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. – jfunk May 31 '16 at 20:17

2 Answers2

65

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

afterEach(function() {
  if (this.currentTest.state === 'failed') {
    // ...
  }
});
Ohad Schneider
  • 36,600
  • 15
  • 168
  • 198
Nevir
  • 7,951
  • 4
  • 41
  • 50
-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'));
  })
})
Kamrul
  • 7,175
  • 3
  • 31
  • 31
  • I saw this in [a mocha.js github issue](https://github.com/visionmedia/mocha/wiki/Conditionally-failing-tests-in-afterEach()-hooks), but I would not be able to set the "this.ok" in each of the prior tests. – omdel Jun 12 '14 at 22:53
  • 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. – Kamrul Jun 13 '14 at 01:27