Skip to main content
WebSocket

JSON Message Protocol

SubscribeParseValidateMedium

Description

Send and receive JSON-formatted messages with proper serialization/deserialization.

Test Scenario

// Test: JSON round-trip
const ws = new WebSocket('wss://echo.websocket.org');
const payload = { type: 'greeting', name: 'Tester', timestamp: Date.now() };

let received: any = null;
ws.onmessage = (e) => { received = JSON.parse(e.data); };

await waitFor(() => ws.readyState === WebSocket.OPEN);
ws.send(JSON.stringify(payload));
await waitFor(() => received !== null);

expect(received.type).toBe('greeting');
expect(received.name).toBe('Tester');

Testing Tips

  • •Use JSON.stringify() before sending
  • •Use JSON.parse() on received data
  • •Handle parsing errors gracefully
// 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-json-messages

2 frameworks available