Reputation: 1268
When running this integration test with Jest in nodeJS:
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);
});
});
With the api.js file:
const PORT = process.env.PORT;
const server = app.listen(PORT, () => {
console.log(`listening on port ${PORT}`);
});
app.use("/api/chat", chat);
module.exports = server;
I get an an error, that it something keeps it up from exiting:
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 |
Any ideas? I checked already on Github but nothing really helped or was just a workaround. How can I properly close the connection?
Upvotes: 4
Views: 6997
Reputation: 2238
I have just started using jest and after few experiments, the following worked for me.
Modify app.js as follows during testing,
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
and on test file use supertest as follows,
// IMPORT app HERE ARE USE IT AS FOLLOWS
await request(app)
.post("/api/chat")
.set("Content-Type", "application/json")
.send({ ...your_payload });
And lastly close db connection,
afterAll(done => {
// THIS IS HOW YOU CLOSE CONNECTION IN MONGOOSE (mongodb ORM)
mongoose.connection.close();
done();
});
Upvotes: 2