Reputation: 6461
I have a test file called integration.test.js
import app from "../app";
import request from "supertest";
describe("testing /users", () => {
const app = request(app);
// 5 test cases here. Both use app for api testing
})
describe("testing /images", () => {
const app = request(app);
// 6 test cases here. Both use app for api testing
})
describe("testing /blogs", () => {
const app = request(app);
// 7 test cases here. Both use app for api testing
})
When I run jest
to run the test cases, it returns a warning
A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try runn
ing with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them.
It also takes around 5 seconds to complete the testing, which seems to be slow
How can I fix the warning and the time of running the test cases?
app.js
import express from "express";
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.get("/", (req, res) => {
res.status(200).send("Hello");
});
app.post("/users", (req, res) => {...});
app.post("/images", (req, res) => {...});
app.post("/blogs", (req, res) => {...});
app.listen(PORT, () => {
console.log(`Server running on ${PORT}`);
});
export default app;
Upvotes: 10
Views: 26364
Reputation: 904
You will need to close the HTTP server on test teardown.
Instead of exporting the express.js app
, you need to export the http.Server
created from app.listen
.
export const server = app.listen(PORT, () => {
console.log(`Server running on ${PORT}`);
});
Pass server
instead of app
into supertest, then on the tests afterAll
hook, call server.close()
:
import { server } from "../app";
import request from "supertest";
describe("testing /users", () => {
const app = request(server);
afterAll(() => {
server.close();
})
// 5 test cases here. Both use app for api testing
})
Upvotes: 2
Reputation: 96544
We struggled with this for a couple of days and finally came up with a fix which works both locally and in our CI (github actions). We were experiencing this issue with using create-react-app plus Firebase-firestore
The trick was that we needed both of the params below to both suppress the message and force the exit.
"test": "react-scripts test --detectOpenHandles --forceExit",
Whether this is covering up a more significant issue remains to be seen
Upvotes: 16
Reputation: 125
I am guessing it's related to asynchronous behaviour, maybe try to use async for test case.
Example:
const supertest = require('supertest')
const app = require('../app')
const api = supertest(app)
describe("testing /users", () => {
test('get all users', async () => {
await api
.get('/api/users')
.expect(200)
.expect('Content-Type', /application\/json/)
})
})
Upvotes: 1