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

it("some_test2", function(){
  // something that could fail

  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(){ /* ... */ })


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

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;

    if (!ok) this.test.error(new Error('something went wrong'));

Need Your Help

Simple way to understand Encapsulation and Abstraction

oop language-agnostic encapsulation abstraction

Learning OOP concepts especially interested to understand Abstraction and Encapsulation in depth.

What is purpose of around_create callback in Rails Model?

ruby ruby-on-rails-3 model callback

when is around_create callback code executed, in what situations we should use it?