微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用简单的 Express 应用程序完成测试运行后,Jest 测试未退出一秒

如何解决使用简单的 Express 应用程序完成测试运行后,Jest 测试未退出一秒

我有一个简单的 Express 应用程序,它公开了一个 RESTful API。它使用 KnexObjection 来访问数据库,并使用 Jest / Supertest 来测试 API。

我有一个测试来启动服务器,从给定的路由中获取可用数据并断言接收到的值。一切正常,除了 Jest 在执行此测试后永远不会退出

这是我的测试:

import { app } from "../../src/application.js";

import { describe,expect,test } from "@jest/globals";
import request from "supertest";

describe("Customer Handler",() => {
  test("should retrieve all existing customer(s)",async () => {
    const expected = [
       // ...real values here; omitted for brevity
    ];
    const response = await request(app).get(`/api/customers`);
    expect(response.statusCode).toStrictEqual(200);
    expect(response.headers["content-type"]).toContain("application/json");
    expect(response.body).toStrictEqual(expected);
  });
});

application.js 文件看起来非常像通常的 Express 设置/配置文件

import { CustomerHandler } from "./handler/customer.handler.js";
import connection from "../knexfile.js";

import express from "express";
import Knex from "knex";
import { Model } from "objection";

const app = express();

Model.knex(Knex(connection[process.env.NODE_ENV]));

// ...removed helmet and some other config for brevity
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/api/customers",CustomerHandler);
app.use((err,req,res,next) => {
  res.status(err.status || 500);
  res.json({
    errors: {
      error: err,message: err.message,},});
  next();
});

export { app };

我尝试了 --detectOpenHandles,但控制台中没有打印任何其他内容,因此我看不到有关问题可能是什么的任何提示 - 我怀疑是 Knex / {{1 }} 因为我使用的是 Objection,所以可能与数据库的连接没有关闭

与此同时,我正在使用 sqlite,但我想弄清楚为什么 --forceExit 无法退出

解决方法

好的,看起来我在这方面走在正确的轨道上。

重构 application.js 以导出 Knex 对象(配置后),并在测试通过后调用 knex.destroy() 是此设置的解决方案。

// application.js

...

const knex = Knex(connection[process.env.NODE_ENV]);

Model.knex(knex);

...

export { app,knex };

...然后在测试中,确保导入 knex 并调用 destroy()

// customer.handler.test.js
import { app,knex } from "../../src/application.js";

import { afterAll,describe,expect,test } from "@jest/globals";
import request from "supertest";

describe("Customer Handler",() => {
  afterAll(async () => {
    await knex.destroy();
  });

  test("should retrieve all existing customer(s)",async () => {
    const expected = [ /* ...real values here */ ];
    ...
    expect(response.body).toStrictEqual(expected);
  });
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。