2.9 KiB
NetworkWebsocketPage
(no submodules)
## PurposeThe 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=senderor?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-statusattribute reflectsidle | connecting | connected | failed- Reconnects when page is navigated away (cleanup via
useEffectreturn) - All required
data-testidattributes 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>headingdemo-card— wraps the status indicator and message areamessage-input— text input for composing messages (sender role only)send-button— sends the current input via WebSocket (sender role only)output— displays received messagesconsole-panel— bottom console section with usage hintsdata-statuson status paragraph — one ofidle | 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.