【发布时间】:2021-07-27 01:05:37
【问题描述】:
我有一个简单的Express 应用程序,它公开了一个 RESTful API。它使用Knex 和Objection 访问数据库,使用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/Objection,因为我是使用SQLite,所以可能与数据库的连接没有关闭。
与此同时,我正在使用
--forceExit,但我想弄清楚为什么Jest无法退出。
【问题讨论】:
-
您可以尝试将参数
done添加到您作为第二个参数传递给test的函数中。然后,完成测试后致电done()。 -
我已经尝试过了,但我收到了这个错误消息:
Test functions cannot both take a 'done' callback and return something. Either use a 'done' callback, or return a promise. Returned value: Promise {}。基本上,我只是做... async (done) => { ...,然后在test(...) {}块的最后调用done()。
标签: node.js jestjs knex.js supertest objection.js