Files
suaveplan/apps/testbed/src/client/pages/network-websocket/network-websocket-page.md
2026-05-27 23:29:53 +01:00

2.9 KiB

NetworkWebsocketPage

(no submodules)

## Purpose

The NetworkWebsocketPage demonstrates real-time bidirectional communication using WebSockets. It connects to the Hono server's /api/ws WebSocket endpoint, joining a named session. Two browser tabs — one as sender and one as receiver — share the same session ID, and messages sent by the sender are broadcast to all other clients in the session.

Features

  • Role-based behaviour (?role=sender or ?role=receiver) driven from URL search params
  • Session ID (?session=<id>) used to namespace the WebSocket room
  • Sender role: text input + Send button to broadcast messages
  • Receiver role: output panel only, shows incoming messages
  • data-status attribute reflects idle | connecting | connected | failed
  • Reconnects when page is navigated away (cleanup via useEffect return)
  • All required data-testid attributes for Playwright E2E testing

Usage: Basic Example

import React from "react";
import { NetworkWebsocketPage } from "./network-websocket-page.js";

// Open two browser tabs:
// Tab 1: http://localhost:3200/network-websocket?role=sender&session=room1
// Tab 2: http://localhost:3200/network-websocket?role=receiver&session=room1

Usage: Advanced Example

In multi-session Playwright tests:

import { createMultiSession } from "@suaveplan/testing-e2e/multi-session";

const { pages, teardown } = await createMultiSession({
  browser,
  count: 2,
  baseUrl: "http://localhost:3200/network-websocket?session=test-room",
  roles: ["sender", "receiver"],
});
const [sender, receiver] = pages;
await expect(sender.locator("[data-status='connected']")).toBeVisible();
await sender.locator('[data-testid="message-input"]').fill("Hello!");
await sender.locator('[data-testid="send-button"]').click();
await expect(receiver.locator('[data-testid="output"]')).toContainText("Hello!");
await teardown();

API Reference

NetworkWebsocketPage(): React.JSX.Element

No props. Role and session ID are read from window.location.search.

data-testid attributes:

  • page-title — the <h1> heading
  • demo-card — wraps the status indicator and message area
  • message-input — text input for composing messages (sender role only)
  • send-button — sends the current input via WebSocket (sender role only)
  • output — displays received messages
  • console-panel — bottom console section with usage hints
  • data-status on status paragraph — one of idle | connecting | connected | failed

Implementation Notes

The WebSocket URL is constructed using window.location.hostname so it works on any port during testing. The useEffect cleanup closes the WebSocket when the component unmounts, preventing connection leaks during navigation. The sender role does not echo sent messages back to itself; the server broadcasts only to other clients in the session.