使用 supertest 和 mongoose 时,测试 运行 完成后 Jest 没有退出一秒

Jest did not exit one second after the test run has completed when using supertest and mongoose

我正在使用 jest 来测试我的 node.js 超级测试端点。

但是在 运行 之后,我的测试笑话没有退出,而是 returns 以下内容并挂起:

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue.

import request from "supertest";
import server from "../../src/index";
import mongoose from "mongoose";

describe("Authentication", () => {

    beforeAll( async () => {
        console.log("Test Starting...");
        await mongoose.connection.dropDatabase();
    });

    afterAll( async () => {
        console.log("... Test Ended");
        await mongoose.connection.dropDatabase();
        await mongoose.connection.close();
    });


    it("should authenticate with basic auth", async (done) => {

        const BASIC_AUTH = Buffer.from(TEST_VARIABLES.HS_USERNAME + ":" + TEST_VARIABLES.HS_PASSWORD).toString("base64");

        const auth_response = await request(server).get("/api/v2/auth/admin")
            .set("Authorization", "Basic " + BASIC_AUTH)
            .expect(200);

        done();

    });

该应用是 node.js 服务器仍在侦听。

server = app.listen(this.config.port, "0.0.0.0");

将 server.close() 添加到 afterAll 解决了问题。

  afterAll( async () => {
        console.log("... Test Ended");
        await mongoose.connection.dropDatabase();
        await mongoose.connection.close();
        app.close()
    });