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 - 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-connect
2 frameworks available