node.js - Jest 没有正确退出
问题描述
在 nodeJS 中使用 Jest 运行此集成测试时:
const request = require("supertest");
let server;
describe("/api/chat", () => {
beforeEach(() => {
server = require("../../api");
});
describe("GET /userlist", () => {
it("show userlist", async () => {
const result = await request(server)
.get("/api/chat/userlist")
.set("X-Auth", process.env.XAuth);
expect(result.status).toBe(200);
});
});
afterAll(done => {
server.close(done);
});
});
使用 api.js 文件:
const PORT = process.env.PORT;
const server = app.listen(PORT, () => {
console.log(`listening on port ${PORT}`);
});
app.use("/api/chat", chat);
module.exports = server;
我收到一个错误,它阻止了它退出:
Jest has detected the following 1 open handle potentially keeping Jest from exiting:
● TCPSERVERWRAP
21 | const PORT = process.env.PORT;
22 |
> 23 | const server = app.listen(PORT, () => {
| ^
24 | console.log(`listening on port ${PORT}`);
25 | });
26 |
有任何想法吗?我已经在 Github 上查看过,但没有任何帮助,或者只是一种解决方法。如何正确关闭连接?
解决方案
我刚刚开始使用 jest,经过几次实验,以下对我有用。
测试时修改app.js如下,
const PORT = process.env.PORT;
// COMMENT THESE
// const server = app.listen(PORT, () => {
// console.log(`listening on port ${PORT}`);
// });
app.use("/api/chat", chat);
module.exports = app; // EXPORT app
并在测试文件上使用 supertest 如下,
// IMPORT app HERE ARE USE IT AS FOLLOWS
await request(app)
.post("/api/chat")
.set("Content-Type", "application/json")
.send({ ...your_payload });
最后关闭数据库连接,
afterAll(done => {
// THIS IS HOW YOU CLOSE CONNECTION IN MONGOOSE (mongodb ORM)
mongoose.connection.close();
done();
});
推荐阅读
- vue.js - vue scss 范围不适用于根元素
- php - 如何将 DB 中的内爆值分配到 Laravel 刀片模板视图中?
- swift - 从其他文件,Swift 在 tabBarController 中呈现 ViewController
- rest - 让 Jersey 2 与嵌入式 Tomcat 一起工作的依赖项是什么
- nonetype - 如何使用django分页?
- vba - 如何在VBA中的第一行之前添加间距?
- javascript - 在此数组解构和初始化对象中的值方面需要帮助
- python - 手写文本的边界框
- ios - 如何在 Core Data 中使用派生属性
- nginx - OpenShift - nginx pod 作为 SSL 终止和负载均衡器