在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上进行了检查,但没有任何帮助或仅仅是一种解决方法。如何正确关闭连接?
答案 0 :(得分:1)
我刚刚开始使用 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();
});