Using NodeJS and Mocha for testing. I think I understand how before() and beforeEach() work. Problem is, I'd like to add a setup script that runs before each "describe" rather than before each "it".
If I use before()
it will run only once for the entire suite, and if I use beforeEach()
it will execute before every single test, so I'm trying to find a middle ground.
So, if this is my test file:
require('./setupStuff');
describe('Suite one', function(){
it('S1 Test one', function(done){
...
});
it('S1 Test two', function(done){
...
});
});
describe('Suite two', function(){
it('S2 Test one', function(done){
...
});
});
I'd like to have "setupStuff" contain a function that runs before 'Suite one' and 'Suite two'
Or, in other words, before 'S1 Test one' and 'S2 Test one' but NOT before 'S1 Test two'.
Can it be done?
you can also do it in this more flexible way:
I have found this approach worked for me, it patches all describe suites.
Differences from the other answers are:
bind
to call thetests
which ensures that if they call functions onthis
, such asthis.timeout(1000)
will still work..skip
and.only
means that you can still use those on your suite, egdescribe.skip
to temporarily suppress suites.describe
function by name allows for a less intrusive injection.tests
andonly
andskip
.There's no call similar to
beforeEach
orbefore
that does what you want. But it is not needed because you can do it this way: