DataTalksClub / DataTalksClub/faq

[AI Dev Tools Zoomcamp] Node.js test runner hangs when testing Socket.io and Express integration

Open Beginner friendly
#397 0 comments 0 reactions 0 assignees View on GitHub

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
  1. Premature port binding: If server.listen(PORT) is executed at the top level of server/index.js, importing the app/server into tests/integration.test.js causes the HTTP server to bind before the test hook can bind to an ephemeral port (0).
  2. Open handles: Socket.io and http.Server maintain persistent event loop connections and internal heartbeat timers, preventing Node's test runner from detecting an empty event loop.
Solution & Best Practice
  1. Guard server.listen in server/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}`);
      });
    }
    
  2. Explicitly close both io and server in the test cleanup hook:

    after(async () => {
      io.close();
      await new Promise((resolve) => serverInstance.close(resolve));
    });
    
  3. Use --test-force-exit in package.json:
    Add --test-force-exit so Node exits cleanly once all tests pass:

    "scripts": {
      "test": "node --test --test-force-exit tests/*.test.js"
    }
    

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.