Last Updated: February 25, 2016
·
4.872K
· jonotron

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

2 Responses
Add your response

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 ·

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 ·