代码之家  ›  专栏  ›  技术社区  ›  Harrison Cramer

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

  •  0
  • Harrison Cramer  · 技术社区  · 5 年前

    我不知道如何构造Jest文件以便进行测试。正常情况下索引.js文件,我正在导入应用程序,然后运行 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.');
    

    我试过在我的测试.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 回复  |  直到 5 年前
        1
  •  0
  •   Harrison Cramer    5 年前

    所以,我不得不做出一些改变。首先,我必须在运行测试之前加载.env文件。我通过创建一个 jest.config.js

    module.exports = {
      verbose: true,
      setupFiles: ["dotenv/config"]
    };
    

    然后在实际的测试套件中,我运行 beforeEach

    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();
      })
    });