Skip to main content
WebSocket

WebSocket Connection

SubscribeValidateEasy

What you will learn

  • Test the full handshake: 101 Switching Protocols, Sec-WebSocket-Accept header โ€” not just open event
  • Authenticate via query param or subprotocol โ€” cookies may be blocked by the browser
  • Test reconnection with exponential backoff โ€” the protocol is stateless about retries

Description

Establish a WebSocket connection to an echo server and verify the connection is open.

Test Scenario

// Test: Verify connection establishment
const ws = new WebSocket('wss://echo.websocket.org');
await waitFor(() => ws.readyState === WebSocket.OPEN);
expect(ws.readyState).toBe(WebSocket.OPEN);
ws.close();

Testing Tips

  • โ€ขUse WebSocket constructor with wss:// URL
  • โ€ขListen for the onopen event
  • โ€ขCheck readyState === WebSocket.OPEN
// Playwright API Testing - WebSocket
import { test, expect } from '@playwright/test';
test('WebSocket connection', async ({ page }) => {
// Listen for WebSocket connections
const wsPromise = page.waitForEvent('websocket');
await page.goto('/websocket-demo');
const ws = await wsPromise;
expect(ws.url()).toContain('ws://');
// Wait for message
const framePromise = ws.waitForEvent('framereceived');
const frame = await framePromise;
expect(frame.payload).toBeDefined();
});

Challenge ID: ws-connect

2 frameworks available