我正在尝试为Express服务器中需要连接到MongoDB数据库的各种路由设置测试。
我不确定如何构造Jest文件以便进行测试。在我正常的index.js文件中,我正在导入应用程序,并在connect app.listen
调用中运行.then
,如下所示:
const connect = require("../dbs/mongodb/connect");
connect()
.then(_ => {
app.listen(process.env.PORT, _ => logger.info('this is running')
})
.catch(_ => logger.error('The app could not connect.');
我已经尝试在test.js文件中运行相同的设置,但无法正常工作。
例如:
const connect = require("../dbs/mongodb/connect");
const request = require("supertest");
const runTests = () => {
describe("Test the home page", () => {
test("It should give a 200 response.", async () => {
let res = await request(app).get("/");
expect(res.statusCode).toBe(200);
});
});
};
connect()
.then(_ => app.listen(process.env.PORT))
.then(runTests)
.catch(err => {
console.error(`Could not connect to mongodb`, err);
});
如何在运行测试之前等待与MongoDB的连接?
答案 0 :(得分:0)
因此,事实证明,我必须进行一些更改。首先,在运行测试之前,我必须加载.env文件。为此,我在项目的根目录中创建了一个jest.config.js
文件:
module.exports = {
verbose: true,
setupFiles: ["dotenv/config"]
};
然后在实际的测试套件中,我正在运行beforeEach
连接到MongoDB服务器。
const connect = require("../dbs/mongodb/connect");
const app = require("../app");
const request = require("supertest");
beforeEach(async() => {
await connect();
});
describe("This is the test", () => {
test("This should work", async done => {
let res = await request(app).get("/home");
expect(res.statusCode).toBe(200);
done();
})
});