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?
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.
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!
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'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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With