请帮助我,我目前正在为Node.js应用程序编写集成测试,但是我无法获取服务器实例来激发请求。
这是服务器配置代码
// server.js
const {
app,
} = require('./config/express');
const {
connect,
} = require('./config/mongo');
const {
port,
} = require('./config/vars');
(async function () {
const connection = await connect();
const db = connection.db;
app.locals.db = db;
app.listen(port, () => {
console.log(`Server is listening on port: ${port}`);
});
})();
module.exports = {
app,
};
上方的匿名函数必须包装在异步中,因为数据库连接connect
是异步函数
// config/mongodb.js
...
module.exports.connect = async () => {
try {
const client = await MongoClient.connect(uri, options);
console.log('Database connection established');
const db = client.db(name);
return {
db,
client,
};
} catch (error) {
console.log('Error connecting to MongoDb');
process.exit(0);
}
};
...
然后,这就是在Model
和Controller
中使用数据库的连接实例的方式。
// model/index.js
class Model {
constructor({ db }) {
this.User = new User(db);
this.video = new Video(db);
this.RefreshToken = new RefreshToken(db);
}
}
module.exports = Model;
// model/user.model.js
class User {
/**
* Create new User instance
* @param {object} collection MongoDb user collection instance
*/
constructor(db) {
this.collection = db.collection('user');
}
// controller/index.js
...
const { db } = req.app.locals;
const { User } = new Model({ db });
...
此配置在我运行服务器时效果很好,但是在测试环境中无法正常工作,这是我编写的集成测试用例的结果
text: `{"code":500,"message":"Cannot read property 'collection' of undefined"}`,
我知道这里的原因是因为app
中的server.js
是在将数据库实例分配给app.locals.db
之前导出的,但是我不知道如何重新使用配置文件,有人可以帮助我吗?