在 运行 Mocha 测试之前等待路由和数据库初始化

Wait for routes and database to initialize before running Mocha tests

我有一个连接到 Mongo 数据库的 NodeJS 应用程序,然后在建立连接后初始化所有路由。我想使用服务器和 supertest 为测试请求添加一些 Mocha 测试。但是,要从 test.js 文件检索服务器,我需要 require() 主文件并从中获取服务器变量。但是,当我尝试使用它时,它会抱怨变量未定义,因为数据库尚未加载且路由尚未初始化。

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

    // ...
});

在 检索 server 变量并继续 Mocha 测试之前,是否有任何方法可以等待数据库和路由初始化

main.js 导出 Promise,例如:

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

然后导入后,在Promise

上调用.then就可以使用了