CodePark/ questions / Isolation, parallelism & flaky tests
START PRACTICINGPRACTICE
Backend question · Backend testing › Isolation, parallelism & flaky tests

Several Nest e2e test files each call await app.listen(3000) in beforeAll. They pass locally but fail randomly in CI with EADDRINUSE. What is the best fix?

Call app.init() instead of listen and pass app.getHttpServer() to supertest, which binds an ephemeral port

The best fix is to call app.init() and pass app.getHttpServer() to supertest. Jest runs test files at the same time in parallel workers. So two files try to use port 3000 at the same moment, and one fails with EADDRINUSE ("address already in use"). supertest doesn't need a server that is already listening. It picks a free port by itself. If you really need a running server, listen(0) also works, because port 0 asks the system for any free port.

"Add
jest.retryTimes(3) to those files" and "Use port 3001 in half of the files" only make the clash happen less often. They don't remove it.