WebSocket
Heartbeat / Keep-Alive
SubscribeValidateMedium
Description
Implement ping/pong heartbeat mechanism to detect connection health.
Test Scenario
// Test: Heartbeat with ping/pong
const ws = new WebSocket('wss://echo.websocket.org');
let pongReceived = false;
ws.onmessage = (e) => {
const msg = JSON.parse(e.data);
if (msg.type === 'ping') pongReceived = true; // Echo acts as pong
};
await waitFor(() => ws.readyState === WebSocket.OPEN);
ws.send(JSON.stringify({ type: 'ping', timestamp: Date.now() }));
await waitFor(() => pongReceived);
expect(pongReceived).toBe(true);Testing Tips
- •Send periodic ping messages
- •Track pong responses
- •Disconnect if pong timeout exceeded
// Playwright API Testing - WebSocketimport { test, expect } from '@playwright/test';test('WebSocket connection', async ({ page }) => {// Listen for WebSocket connectionsconst wsPromise = page.waitForEvent('websocket');await page.goto('/websocket-demo');const ws = await wsPromise;expect(ws.url()).toContain('ws://');// Wait for messageconst framePromise = ws.waitForEvent('framereceived');const frame = await framePromise;expect(frame.payload).toBeDefined();});
Challenge ID: ws-ping-pong
2 frameworks available