Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Created November 11, 2015 22:41
Show Gist options
  • Save cowboyd/f5611829c7a3ad084642 to your computer and use it in GitHub Desktop.
Save cowboyd/f5611829c7a3ad084642 to your computer and use it in GitHub Desktop.
Demonstrate Mocha not running `beforeEach` hooks on outer contexts when using grep.

Running lifecycle hooks with a mocha grep

given the following mocha code:

describe("the outer context", function () {
  beforeEach(function() {
    this.didRunBeforeEach = true;
  });
  describe("the inner context", function() {
    it("runs its parent beforeEach", function() {
      expect(this.didRunBeforeEach).to.equal(true);
    });
  }) ;
});

because "the inner context" is nested inside "the outer context", it should run the outer context's beforeEach hook. It does do this under normal circumstances:

~/C/E/mocha-demo ❯❯❯ npm t

> mocha-demo@1.0.0 test /Users/cowboyd/Code/Ember/mocha-demo
> mocha index.js



  the outer context
    the inner context
       runs its parent beforeEach


  1 passing (7ms)

But if we configure the inner context to use it.only to select only the single test-case:

describe("the outer context", function () {
  beforeEach(function() {
    this.didRunBeforeEach = true;
  });
  describe("the inner context", function() {
    it.only("runs its parent beforeEach", function() {
      expect(this.didRunBeforeEach).to.equal(true);
    });
  }) ;
});

Then it fails with the following error:

~/C/E/mocha-demo ❯❯❯ npm t                                                                                                                                                                                                                  ⏎

> [email protected] test /Users/cowboyd/Code/Ember/mocha-demo
> mocha index.js


  1) runs its parent beforeEach

  0 passing (9ms)
  1 failing

  1)  runs its parent beforeEach:
     AssertionError: expected undefined to equal true
      at Context.<anonymous> (index.js:15:40)



npm ERR! Test failed.  See above for more details.

Which indicates that the hook is either not being run.

/*global require */
var mocha = require('mocha'),
expect = require('chai').expect,
describe = mocha.describe,
it = mocha.it,
beforeEach = mocha.beforeEach;
describe("the outer context", function () {
beforeEach(function() {
this.didRunBeforeEach = true;
});
describe("the inner context", function() {
it.only("runs its parent beforeEach", function() {
expect(this.didRunBeforeEach).to.equal(true);
});
}) ;
});
{
"name": "mocha-demo",
"version": "1.0.0",
"description": "Demonstrate strange behavior in mocha",
"main": "index.js",
"scripts": {
"test": "mocha index.js"
},
"author": "",
"license": "MIT",
"devDependencies": {
"chai": "^3.4.1",
"mocha": "^2.3.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment