我有一个NodeJS应用程序连接到Mongo数据库,然后在建立连接后初始化所有路由。我想使用服务器添加一些Mocha测试,并为测试请求添加supertest
。但是,要从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
变量并继续进行摩卡测试?
答案 0 :(得分:4)
让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));
});
});
然后,导入后,您可以在.then
Promise
后使用它