DataTalksClub / DataTalksClub/faq
[AI Dev Tools Zoomcamp] Node.js test runner hangs when testing Socket.io and Express integration
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 7
- Forks
- 19
- Avg merge
- 3d 20h
- Merged PRs (30d)
- 9
Description
Course & Homework
- Course: AI Dev Tools Zoomcamp (2026)
- Module: Homework 2 - Build and Ship an AI-Assisted Full-Stack App
Problem Description
When running integration tests for a collaborative full-stack application using Node.js's built-in test runner (node --test) against an Express and Socket.io server, the test process hangs indefinitely in the terminal after executing, or fails with ERR_SERVER_ALREADY_LISTEN.
Root Cause
- Premature port binding: If
server.listen(PORT)is executed at the top level ofserver/index.js, importing the app/server intotests/integration.test.jscauses the HTTP server to bind before the test hook can bind to an ephemeral port (0). - Open handles: Socket.io and
http.Servermaintain persistent event loop connections and internal heartbeat timers, preventing Node's test runner from detecting an empty event loop.
Solution & Best Practice
-
Guard
server.listeninserver/index.js:
Ensure the server only listens when executed directly, not when imported by test suites:if (require.main === module) { server.listen(PORT, () => { console.log(`Server listening on port ${PORT}`); }); } -
Explicitly close both
ioandserverin the test cleanup hook:after(async () => { io.close(); await new Promise((resolve) => serverInstance.close(resolve)); }); -
Use
--test-force-exitinpackage.json:
Add--test-force-exitso Node exits cleanly once all tests pass:"scripts": { "test": "node --test --test-force-exit tests/*.test.js" }
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the issue's proposed changes for server/index.js, tests/integration.test.js, and package.json. Verify that the documented guidance covers guarded server startup, cleanup of Socket.io and the HTTP server, and the test command; it is done when the FAQ clearly explains how to prevent the hang or ERR_SERVER_ALREADY_LISTEN failure.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- express, javascript, node.js
- Domain
- backend, documentation, testing-qa
- Issue type
- Documentation
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Active
- Clarity
- Clearly specified
- Newbie friendliness
- 85/100