如何在NodeJS项目中使用Jest全局安装和拆卸?

我使用JEST将测试添加到我的节点js项目中,但是对于每个测试套件,都有一个beforeAll方法,用于创建新的测试服务器并连接到mongo数据库,以及一个After all方法,用于关闭测试服务器和数据库。我想为所有测试套件全局执行上述任务,而不是一次执行一个。下面是我的代码示例。

app.js

const express = require("express");
const app = express();
const { connectToDb } = require("./startup/db");
require("./startup/routes")(app);
connectToDb();
...

const port = process.env.PORT || 3000;

if (process.env.NODE_ENV !== "test") {
  app.listen(port, () => winston.info(`Listening on port ${port}...`));
}

module.exports = app;

auth.test.js

const request = require("supertest");
const http = require("http");
const { disconnectDb } = require("../../startup/db");

describe("auth middleware", () => {
  let server;

  beforeAll((done) => {
    const app = require("../../app");
    server = http.createServer(app);
    server.listen(done);
  });

  afterAll((done) => {
    server.close(done);
    disconnectDb();
  });

  it("should return 401 if no token is provided", async () => {
    const res = request(server)
      .post("/api/genres")
      .set("x-auth-token", "")
      .send({ name: "genre1" });
    expect(res.status).toBe(401);
  });

...

jest.config.js

module.exports = {
  testEnvironment: "node",
};

解决方案

尝试使用此jest.config.js:

module.exports = {
  testEnvironment: "node",
  globalSetup: '<rootDir>/src/testSetup.ts'
};

在testSetup.ts中您可以执行以下操作:

// testSetup.ts
module.exports = async () => {
    const app = require("../../app");
    server = http.createServer(app);
    server.listen(done);
};

相关文章