简体   繁体   中英

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?

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'); });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM