Call beforeEach and afterEach with nested description blocks

I am trying to get some logic to be called before and after each nested description of the test suite for jasmine that I am writing.

I now have something like this:

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 find my functions in beforeEach and afterEach for each it inside my internal description. I want them to be called only once for each internal description that I have in the external.

Is it possible?

+10
javascript jasmine
source share
2 answers

I think you should use "beforeAll" and "afterAll" for the specifications inside the description. The following is taken from the jasmine website: http://jasmine.imtqy.com/2.1/introduction.html

The beforeAll function is called only once before running all the specifications in the description, and the afterAll function is called after all the specifications have completed. These features can be used to speed up test suites with expensive tuning and disruption.

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

+4
source share

To do this, I define a generic function and then reference it in the beforeAll / afterAll 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); }); }); 

This seems to be the cleanest solution available.

+1
source share

All Articles