Gustav
Gustav

Reputation: 3586

jasmine beforeAll affected by sibling describe

I was under the impression that the beforeAll-function would run once for the describe it was inside. However it seems that sibling describes can affect the beforeAll.

the following tests can be found here

describe("outer Describe", function(){
    var testArray;
    beforeEach(function(){
      testArray = [];
    });
    describe("First Describe", function(){
      beforeEach(function(){
        testArray.push({name: "foo"});
      });

      it("has an item", function(){
        expect(testArray.length).toBe(1);//passing
      });
    });

    describe("Second describe", function(){
      var arrIsEmptyInBeforeAll;
      var arrIsEmptyInBeforeEach;
      beforeAll(function(){
        arrIsEmptyInBeforeAll = testArray.length === 0;
        console.log("testArray should be empty:");
        console.log(testArray);//logs array with one item
      });

      beforeEach(function(){
        arrIsEmptyInBeforeEach = testArray.length === 0;
      });

      it("the arr was empty in before all", function(){
        expect(arrIsEmptyInBeforeAll).toBeTruthy(); //This is failing
      });

      it("the arr was empty in beforeEach", function(){
        expect(arrIsEmptyInBeforeEach).toBeTruthy();//Passing
      })
    })
  });

I would expect that the beforeAll inside the "Second Describe" would have an empty testArray, because the "outer Describe" has a beforeEach that initializes it as an empty array. However, in the beforeAll of "Second Describe", the testArray has the one item added in "First Describe"'s beforeEach.

Does this make sense? If so, could someone explain how beforeAll is supposed to work.

Upvotes: 1

Views: 193

Answers (1)

philsch
philsch

Reputation: 1044

Note: You've a typo in your code ;) .. but that's not the problem.

expect(arrIsEmptyInBeforeAll).toBeTruthy();

short answer

beforeAll is always called before beforeEach in Jasmine, even if there are outer beforeEach statements.

Your test is executed the following way:

(Iteration of outer tests)

  1. Outer beforeEach is called -> array is empty
  2. "First Describe" beforeEach is called -> array becomes length = 1

(Iteration of inner tests)

  1. "Second describe" beforeAll is called -> arrIsEmptyInBeforeAll is false because array is still set with one item
  2. Outer beforeEach is called -> array is empty
  3. "Second describe" beforeEach is called -> arrIsEmptyInBeforeEach is true because array was cleared
  4. arrIsEmptyInBeforeAll is false in your test

Upvotes: 2

Related Questions