|

WebSocket Testing With Playwright: Real-Time Apps, Chat, Live Dashboards

Chat apps, live dashboards, trading platforms, multiplayer games — all use WebSockets. Traditional HTTP testing tools cannot test them. Here is how.

🎭 Want to master this with real projects? Join the Playwright Automation Mastery course at The Testing Academy.

Contents

WebSocket vs HTTP for Testers

HTTPWebSocket
Request-responsePersistent bidirectional
Client initiatesEither side sends anytime
StatelessStateful connection
Status codesMessage-based

Testing with Playwright

test('chat message sent and received', async ({ page }) => {
  // Listen for WebSocket frames
  const wsMessages: string[] = [];
  page.on('websocket', ws => {
    ws.on('framereceived', event => wsMessages.push(event.payload.toString()));
    ws.on('framesent', event => wsMessages.push('SENT: ' + event.payload.toString()));
  });

  await page.goto('/chat');
  await page.getByLabel('Message').fill('Hello World');
  await page.getByRole('button', { name: 'Send' }).click();

  // Verify message appears in UI
  await expect(page.getByText('Hello World')).toBeVisible();

  // Verify WebSocket frame was sent
  expect(wsMessages.some(m => m.includes('Hello World'))).toBeTruthy();
});

🚀 Level Up Your Playwright

From locators to CI pipelines — build a production-grade Playwright + TypeScript framework step by step.

Mocking WebSocket with routeWebSocket

test('handle WebSocket server messages', async ({ page }) => {
  await page.routeWebSocket('**/ws', route => {
    const server = route.connectToServer();

    // Intercept and modify messages
    route.onMessage(message => {
      console.log('Client sent:', message);
      server.send(message); // Forward to real server
    });

    // Inject fake server message
    setTimeout(() => {
      route.send(JSON.stringify({ type: 'notification', text: 'New order received' }));
    }, 1000);
  });

  await page.goto('/dashboard');
  await expect(page.getByText('New order received')).toBeVisible({ timeout: 5000 });
});

WebSocket Test Scenarios

  • Connection establishment: Verify WebSocket connects successfully
  • Message format: Validate JSON structure of sent/received messages
  • Reconnection: Kill connection, verify auto-reconnect behavior
  • Authentication: Test token-based WebSocket auth
  • Rate limiting: Send rapid messages, verify server handles gracefully
  • Concurrent connections: Multiple tabs connected simultaneously
  • Connection timeout: Idle connection handling
  • Binary data: File transfer over WebSocket

Native WebSocket Testing (No Browser)

import WebSocket from 'ws';

test('WebSocket echo server', async () => {
  const ws = new WebSocket('ws://localhost:3000/ws');

  const response = await new Promise<string>((resolve) => {
    ws.on('open', () => ws.send('ping'));
    ws.on('message', (data) => resolve(data.toString()));
  });

  expect(response).toBe('pong');
  ws.close();
});

🎓 Master Playwright End to End

Join hundreds of SDETs building real automation frameworks. Lifetime access, hands-on projects, and a job-ready portfolio.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.