terpak terpak - 4 months ago 13
Node.js Question

How can I build my test suite asynchronously?

I'm trying to create mocha tests for my controllers using a config that has to be loaded async. Below is my code. However, when the mocha test is run, it doesn't run any tests, displaying

0 passing
. The
console.log
s are never even called. I tried doing
before(next => config.build().then(next))
inside of the describe, but even though the tests run,
before
is never called. Is there a way to have the config be loaded one time before any tests are run?

'use strict';

const common = require('./common');
const config = require('../config');

config
.build()
.then(test);


function test() {
console.log(1);
describe('Unit Testing', () => {
console.log(2);
require('./auth');
});
}

Answer

You should run Mocha with the --delay option, and then use run() once you are done building your test suite. Here is an example derived from the code you show in the question:

'use strict';

function test() {
    console.log(1);
    describe('Unit Testing', () => {
        console.log(2);
        it("test", () => {
            console.log(3);
        });
    });

    // You must use --delay for `run()` to be available to you.
    run();
}

setTimeout(test, 1000);

I'm using setTimeout to simulate an asynchronous operation. Using --delay and run() allows you to build a suite that is the result of an asynchronous computation. Note, however, that the suite must be built in one shot. (You cannot have an asynchronous process inside describe that will make calls to it. This won't work.)

Comments