jz3bza
Last Updated: February 25, 2016
·
3.875K
· jonotron
591e18d6de648d077d486d607988d9ba

series steps in mocha beforeEach

mocha's beforeEach allows you to create multiple series steps that need to run before your tests run. Up until now I've been doing a combination of callback nesting or async workflows. Seems obvious now that beforeEach just creates a list of operations to execute.

Occasionally you need to do multiple asynchronous things before a test, for example:

beforeEach(function(done) {
    loadSomeData(function() {
        setSomeOtherTestVariables(done);
    });
});

Nesting callbacks is gross, so you may decide to improve readability with async:

beforeEach(function(done) {
    async.series([
        loadSomeData,
        setSomeOtherTestVariables
    ], done);
});

A simpler method is to just use multiple beforeEach calls:

beforeEach(function(done) {
    loadSomeData(done);
});

beforeEach(function(done) {
    setSomeOtherTestVariables(done);
});

You probably still need to use something like async for parallel operations, but for series operations this works quite well

Say Thanks
Respond

2 Responses
Add your response

6385
670efd06d01b46e668fb284f1258add9

A simpler method is to just use multiple beforeEach calls

What is the point of wrapping the "steps" into anonymous functions in this case? :)

over 1 year ago ·
6386
591e18d6de648d077d486d607988d9ba

In this example, there is no point (other than for illustration I suppose). The next step in refactoring would be to just pass the "steps" into beforeEach:

beforeEach(loadSomeData);
beforeEach(setSomeOtherTestVariables);
over 1 year ago ·