mocha is a JavaScript test framework running on Node.js and in the browser.

  1. describe, it, before and done
  2. before vs beforeEach
  3. after vs afterEach

Version for this test. "mocha": "5.1.1" "node": "9.2.1"

Inside a describe, before will execute **once** before **all tests** inside this describe including nested tests. Inside a describe, beforeEach will execute **once** before **every test** inside this describe including nested tests. In other words, if there are **N** tests in total (including nested tests), beforeEach will execute **N** times in total.
// before vs beforeEach
describe("Describe(1)", () => {
  let i = 0;
  let j = 0;
  before(() => {
    console.log("outer before(1) executed once in Describe(1)");
  });
  beforeEach(() => {
    console.log(i + ",outer beforeEach(1) executed in Describe(1)");
    i++;
  });
  it("outer test1", () => {
    console.log("outer test1 in Describe(1)");
  });
  it("outer test2", () => {
    console.log("outer test2 in Describe(2)");
  });
  describe("Describe(2)", function () {
    before(() => {
      console.log("inner before(2) executed in Describe(2)");
    });
    beforeEach(() => {
      console.log(j + ",inner beforeEach(2) executed in Describe(2)");
      j++;
    });
    it("inner test1", () => {
      console.log("inner test1");
    });
    it("inner test2", () => {
      console.log("inner test2");
    });
  });
  it("outer test3", () => {
    console.log("outer test3");
  });
});
The output is
Describe(1)
outer before(1) executed once in Describe(1)
0,outer beforeEach(1) executed in Describe(1)
outer test1 in Describe(1)
    ✓ outer test1
1,outer beforeEach(1) executed in Describe(1)
outer test2 in Describe(2)
    ✓ outer test2
2,outer beforeEach(1) executed in Describe(1)
outer test3
    ✓ outer test3
    Describe(2)
inner before(2) executed in Describe(2)
3,outer beforeEach(1) executed in Describe(1)
0,inner beforeEach(2) executed in Describe(2)
inner test1
      ✓ inner test1
4,outer beforeEach(1) executed in Describe(1)
1,inner beforeEach(2) executed in Describe(2)
inner test2
      ✓ inner test2


  9 passing (11ms)
The outer before(1) executed once. The outer beforeEach(1) executed 5 times, since there are 5 tests(`inner test1`, `inner test2`, `outer test1`, `outer test2`, `outer test3`) in total within the beforeEach(1). The inner beforeEach(2) executed twice, since there are 2 tests(`inner test1`, `inner test2`) within the beforeEach(2).

Hope this blog could help you understand the before, beforeEach, after, afterEach, itmocha test.



Related Posts