Pal Kerecsenyi
Pal Kerecsenyi

Reputation: 567

Wait for routes and database to initialize before running Mocha tests

I have a NodeJS app that connects to a Mongo database and then initializes all the routes once the connection has been established. I want to add some Mocha tests using a server and supertest for test requests. However, to retrieve the server from the test.js file, I need to require() the main file and get the server variable from it. When I try to use it however, it complains that the variable is undefined, as the database hasn't loaded and the routes haven't been initialised.

main.js (extract)

// This is a custom mongo module that connects using my db string
// It stores the DB as a variable in another file, which is later retrieved by the route handlers using mongo.GetDB()

mongo.ConnectToDB(function(err, dbo){
    if(err) throw err;

    require("./api")(app);
    require("./admin")(app);
    require("./routes")(app);
});

// This obviously doesn't work, as it's outside of the callback
module.exports.server = app.listen(4500);

server.test.js (extract)

describe("loading express", (done) => {
    let server;
    beforeEach(() => {
        // The server is returned, but none of the routes are included
        server = require("../main").server;
    });

    afterEach(() => {
        server.close();
    });

    // ...
});

Is there any way to wait for the database and the routes to initialize before the server variable is retrieved and the Mocha tests continue?

Upvotes: 0

Views: 1191

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370599

Have main.js export a Promise instead, something like:

module.exports.serverPromise = new Promise((resolve, reject) => {
  mongo.ConnectToDB(function(err, dbo){
    if(err) reject(err);
    require("./api")(app);
    require("./admin")(app);
    require("./routes")(app);

    resolve(app.listen(4500));
  });
});

Then, after importing it, you can use it after calling .then on the Promise

Upvotes: 4

Related Questions