Anthony O
Anthony O

Reputation: 672

How can I synchronously call asynchronous functions sequentially within the Mocha Test Framework?

Please do not suggest mocking the DB models as that is not an option that is available to me, I know that it is a better way to test.

I have several database models that must be created in the following order:

A -> B -> C -> D

I am using Sequelize and the Mocha test framework. I want to create these models as part of the test setup in my test database.

describe('My Tests', () => {
    before(done => {
         models.aModel.create({ name: 'A'}).then((a) => { done(); });
         models.bModel.create({ name: 'B'}).then((b) => { done(); });
         models.cModel.create({ name: 'C'}).then((c) => { done(); });
         models.dModel.create({ name: 'D'}).then((d) => { done(); });
    });
});

So obviously this does not work. In pseudocode all I want to do is:

describe('My Tests', () => {

    before(done => {
        await creation of a
        await creation of b
        await creation of c
        await creation of d
    });
});

How do I do this?

Upvotes: 0

Views: 47

Answers (2)

Thomas Sablik
Thomas Sablik

Reputation: 16448

You can simply chain the calls:

describe('My Tests', () => {
    before(done => {
         models.aModel.create({ name: 'A'})
         .then(() => models.bModel.create({ name: 'B'}))
         .then(() => models.cModel.create({ name: 'C'}))
         .then(() => models.dModel.create({ name: 'D'}))
         .then(() => { done(); });
    });
});

function f(str) {
    console.log('Started: ' + str);
    return new Promise(resolve => { console.log('finished: ' + str); resolve(); });
}

f('a')
.then(() => f('b'))
.then(() => f('c'))
.then(() => f('d'))
.then(() => { console.log('done'); });

Upvotes: 2

Carlos Jafet Neto
Carlos Jafet Neto

Reputation: 891

Try somethig like this:

 before(async function () { 
        await models.aModel.create({ name: 'A'});
        await models.bModel.create({ name: 'B'});
        await models.cModel.create({ name: 'C'});
        await models.dModel.create({ name: 'D'});

 })

Inside an async function you can await for a promise to resolve.

Upvotes: 2

Related Questions