37

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?

1
  • 1
    In case it helps someone. When I have nested describe blocks, using beforeEach in the top level describe will run the code before every test, including nested tests. I'm using vitest. You can test this with beforeEach(() => console.error("HELLO")) and read the output. Commented Apr 3, 2023 at 16:38

2 Answers 2

22

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.

0
9

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.

2
  • 2
    Thanks but I have seen this documentation already and it doesn't help in my scenario
    – mindparse
    Commented Jun 20, 2016 at 16:21
  • 2
    I know it's 4 years late but for future readers what @Ram Pasala is saying is exactly what one would need. That or you can put beforeEach outside of the parent describe.
    – shriek
    Commented Sep 4, 2019 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.