Reputation: 2283
I have a test suite using Mocha with nested describe and beforeEach blocks. When I run the tests I expect the outer beforeEach to run before the inner beforeEach
Here is some sample code
const expect = require('chai').expect
describe('Outer describe', async () => {
beforeEach(() => {
console.log('Outer beforeEach is running!!!!');
});
afterEach(() => {
console.log('Outer afterEach is running!!!!');
});
it('Outter test', async () => {
expect(true).to.be.true;
});
describe('Inner describe', () => {
before(() => {
console.log('Inner beforeEach is running!!!!');
});
after(() => {
console.log('Inner afterEach is running!!!!');
});
// only used to simplify the output
it.only('Inner test', async () => {
expect(true).to.be.true;
});
})
});
He is the output from running the above tests
Outer describe
Inner describe
Inner beforeEach is running!!!!
Outer beforeEach is running!!!!
✓ Inner test
Outer afterEach is running!!!!
Inner afterEach is running!!!!
What I was expecting was
Outer describe
Inner describe
Outer beforeEach is running!!!!
Inner beforeEach is running!!!!
✓ Inner test
Inner afterEach is running!!!!
Outer afterEach is running!!!!
Is this expected behaviour? My inner beforeEach depends on my outer beforeEach running before it, is this considered bad practice?
I'm using
Node 14.11.0
Mocha 8.1.3
Upvotes: 1
Views: 1317
Reputation: 2283
The reason the output is not as expected is the inner describe is using a before
instead of beforeEach
before
only runs once before all tests in the describe block and beforeEach
runs before every test in the describe block. This means the outer describe's beforeEach
needs to run after the inner before
Upvotes: 1