Calling beforeEach and afterEach with nested describe blocks

25,308

Solution 1

To accomplish this I define a common function and then refer to it in the beforeAll/afterAll of each nested describe.

describe('Wrapper', function() {
  var _startup = function(done) {
    login();
    window.setTimeout(done, 150);
  };

  var _shutdown = function() {
    logout();
  };

  describe('Inner 1', function() {
    beforeAll(_startup);
    afterAll(_shutdown);
  });

  describe('Inner 2', function() {
    beforeAll(_startup);
    afterAll(_shutdown);
  });

  describe('Inner 3', function() {
    beforeAll(_startup);
    afterAll(_shutdown);
  });
});

It seems to be cleanest solution available.

Solution 2

I think you should use 'beforeAll' and 'afterAll',for specs inside a describe. following is taken from jasmine website : http://jasmine.github.io/2.1/introduction.html

The beforeAll function is called only once before all the specs in describe are run, and the afterAll function is called after all specs finish. These functions can be used to speed up test suites with expensive setup and teardown.

However, be careful using beforeAll and afterAll! Since they are not reset between specs, it is easy to accidentally leak state between your specs so that they erroneously pass or fail.

Share:
25,308
mindparse
Author by

mindparse

Updated on May 28, 2020

Comments

  • mindparse
    mindparse about 4 years

    I'm trying to get some logic to be called before and after each nested describe of a jasmine test suite I'm writing.

    I have something like this right now:

    describe('Outer describe', function () {
        beforeEach(function () {
            login();
            someOtherFunc();
        });
    
        afterEach(function () {
            logout();
        });
    
        describe('inner describe', function () {
            it('spec A', function () {
                    expect(true).toBe(true);
            });
    
            it('spec B', function () {
                    expect(true).toBe(true);
            });
        });
    });
    

    I'm finding my functions in the beforeEach and afterEach are called for each it inside my inner describe. I only want these to be called once for each inner describe I have in the outer one.

    Is this possible?