Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling beforeEach and afterEach with nested describe blocks

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?

like image 621
mindparse Avatar asked Jun 19 '16 22:06

mindparse


People also ask

Does beforeEach run before each describe?

beforeEach(fn) This is often useful if you want to reset some global state that will be used by many tests. Here the beforeEach ensures that the database is reset for each test. If beforeEach is inside a describe block, it runs for each test in the describe block.

Which function is called before each test specification is run?

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!

Does beforeAll run before beforeEach?

The other behaviour here to consider is that the nested-beforeAll actually runs before the top-beforeEach , meaning that if your nested-beforeAll was relying on the top-beforeEach to have run before the block was entered, you're going to be out of luck.

What is before each and after each?

What's the difference between beforeEach/afterEach and setup/teardown? The difference is beforeEach()/afterEach() automatically run before and after each tests, which 1. removes the explicit calls from the tests themselves, and 2. invites inexperienced users to share state between tests.


1 Answers

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.

like image 62
Kyle Avatar answered Sep 20 '22 13:09

Kyle