Monitoring WebSockets and Real-Time Streams
Learn how to use Playwright to monitor real-time applications using WebSockets. Verify connections, message payloads, and streaming latency.
Real-time applications—like trading platforms, chat apps, and live dashboards—require more than just HTTP checks. You need to verify that your WebSocket handshake succeeds and that messages are flowing with low latency.
WebSocket Monitoring Patterns
Playwright allows you to listen to WebSocket events directly within your check script.
1. Verifying the Handshake
Ensure your server is accepting new WebSocket connections.
import { test, expect } from '@playwright/test';
test('websocket handshake succeeds', async ({ page }) => {
// Listen for the 'websocket' event
const [waitForWebSocket] = await Promise.all([
page.waitForEvent('websocket'),
page.goto('/live-dashboard')
]);
expect(waitForWebSocket.url()).toContain('wss://api.your-app.com');
});2. Asserting on Inbound Messages
Verify that your backend is sending the correct data format over the socket.
test('receives live price updates', async ({ page }) => {
await page.goto('/trading');
const ws = await page.waitForEvent('websocket');
// Wait for a frame containing 'price_update'
const frame = await ws.waitForFrameReceived(payload => {
const data = JSON.parse(payload.toString());
return data.type === 'price_update';
});
const message = JSON.parse(frame.toString());
expect(message.symbol).toBe('BTC');
expect(message.price).toBeGreaterThan(0);
});3. Monitoring Latency
You can measure the time between an action (like a "Send" click) and the server's WebSocket response.
test('chat latency is under 500ms', async ({ page }) => {
await page.goto('/chat');
const ws = await page.waitForEvent('websocket');
const start = performance.now();
await page.getByPlaceholder('Type a message...').fill('Hello World');
await page.keyboard.press('Enter');
await ws.waitForFrameReceived(payload => payload.toString().includes('Hello World'));
const end = performance.now();
expect(end - start).toBeLessThan(500);
});Best Practices for Real-Time Monitoring
- Handle Timeouts Gracefully: WebSocket events can take longer than HTTP. Use appropriate
timeoutsettings inwaitForEvent. - Verify Binary Data: If using Protobuf or MsgPack, use
payload.buffer()to inspect the raw data. - Isolate the Socket: If your app uses multiple sockets, filter by URL to ensure you're monitoring the right stream.
Advanced Playwright
Playwright Tips & Best Practices for Reliable Tests
Write more reliable Playwright tests with proper selectors, auto-waiting, authentication state reuse, parallel testing, and debugging techniques.
What is Playwright? A Complete Guide to Browser Automation
Learn what Playwright is, how it works, and why it's become the leading choice for end-to-end testing and browser automation. Covers architecture, features, and real-world use cases.