-
-
Save harto/c97d2fc9d0bfaf20706eb2acbf48c908 to your computer and use it in GitHub Desktop.
'use strict'; | |
describe('mocha before hooks', function () { | |
before(() => console.log('*** top-level before()')); | |
beforeEach(() => console.log('*** top-level beforeEach()')); | |
describe('nesting', function () { | |
before(() => console.log('*** nested before()')); | |
beforeEach(() => console.log('*** nested beforeEach()')); | |
it('is a nested spec', () => true); | |
}); | |
}); | |
// mocha before hooks | |
// *** top-level before() | |
// nesting | |
// *** nested before() | |
// *** top-level beforeEach() | |
// *** nested beforeEach() | |
// ✓ is a nested spec | |
// | |
// | |
// 1 passing (8ms) |
Is there a way to get a global beforeEach() to run before every nexted before() statement?
top level beforeEach
initializes something that is used by the nested before
Thanks @harto, I came here looking for exactly this insight.
Thanks for this! I was having a hard time figuring out what was wrong with my tests.
Is there a way to run a hook before and after each spec?
Eg, there are 3 *.spec.js
files
The console should print..
Test started at : 12:00:00
Spec 1 tests
...
...
Test Ended at : 12:00:10
Test started at : 12:00:11
Spec 2 tests
...
...
Test Ended at : 12:00:15
Test started at : 12:00:15
Spec 3 tests
...
...
Test Ended at : 12:00:20
Thanks for this. I was trying to access a nested object property within the nested describe
block and getting a TypeError because the beforeEach
hook in the top-level describe
, where the object was being assigned, was not being called prior to that so the object was in fact undefined.
before
describe('top-level', () => {
let obj;
beforeEach(() => {
obj = {
nested: {
property: 'value'
}
};
});
describe('nested', () => {
obj.nested.property = 'new-value';
});
});
after
describe('top-level', () => {
let obj;
beforeEach(() => {
obj = {
nested: {
property: 'value'
}
};
});
describe('nested', () => {
beforeEach(() => {
obj.nested.property = 'new-value';
});
});
});
this was very helpful!
Thank you!
top level
beforeEach
initializes something that is used by the nestedbefore
From the example above the nested before()
is called before the top level beforeEach()
.
So if the nested before()
relies on the top level beforeEach()
to initialize something, the result might be undefined
or null
This helped me understand the order in which
before()
andbeforeEach()
fire within a nesteddescribe()
(orcontext()
).My initial (wrong) intuition was that the top-level
beforeEach()
would fire before every nesteddescribe()
(and hence before every nestedbefore()
), but of coursebefore()
/beforeEach()
apply to specs (i.e.it()
), not scopes.