【问题标题】:How to test with Jest after connecting to MongoDB?连接 MongoDB 后如何使用 Jest 进行测试?
【发布时间】:2020-07-04 13:05:25
【问题描述】:

我正在尝试为我的 Express 服务器中需要连接到我的 MongoDB 数据库的各种路由设置测试。

我不确定如何构建 Jest 文件以进行测试。在我的普通 index.js 文件中,我正在导入应用程序,并在 connect .then 调用中运行 app.listen,如下所示:

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】:

    所以,我不得不做出一些改变。首先,我必须在运行测试之前加载我的 .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();
      })
    });
    

    【讨论】:

      猜你喜欢
      • 2018-11-09
      • 2020-12-02
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      • 2021-03-05
      • 2020-05-20
      • 1970-01-01
      • 2019-04-30
      相关资源
      最近更新 更多