Skip to content

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

Description

@c-ibarra

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"
    }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions