连接到MongoDB后如何用Jest测试?

问题描述 投票:0回答:1

我正在尝试为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的连接?

javascript mongodb express jestjs supertest
1个回答
0
投票
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();
  })
});
© www.soinside.com 2019 - 2024. All rights reserved.