Testing WebRTC Applications: A Practical Guide

Testing WebRTC Applications: A Practical Guide

WebRTC is one of the hardest browser APIs to test. It involves multiple async negotiation steps (offer/answer/ICE), media device access, NAT traversal, and peer-to-peer connections that are inherently network-dependent. Most teams either skip testing WebRTC entirely, or test only the signaling layer and hope the rest works.

This guide covers practical testing strategies across the full WebRTC stack.

The WebRTC Testing Layers

WebRTC applications have four testable layers:

  1. Signaling server — your WebSocket/HTTP server that exchanges SDP offers/answers and ICE candidates between peers
  2. Client signaling logic — the JavaScript code that calls createOffer, setLocalDescription, etc.
  3. Connection establishment — that peers actually connect, including ICE negotiation
  4. Media — that audio/video streams are correctly acquired, transmitted, and rendered

Each layer needs different test strategies. Start from the bottom up.

Testing the Signaling Server

The signaling server is pure WebSocket or HTTP — test it as you would any real-time server. Here's a typical signaling server and its tests:

// signaling-server.js
const { WebSocketServer } = require('ws');

function createSignalingServer(port) {
  const wss = new WebSocketServer({ port });
  const rooms = new Map(); // roomId → Set of clients

  wss.on('connection', (ws) => {
    let currentRoom = null;

    ws.on('message', (data) => {
      const msg = JSON.parse(data.toString());

      if (msg.type === 'join') {
        currentRoom = msg.room;
        if (!rooms.has(currentRoom)) rooms.set(currentRoom, new Set());
        rooms.get(currentRoom).add(ws);
        ws.send(JSON.stringify({
          type: 'joined',
          room: currentRoom,
          peers: rooms.get(currentRoom).size - 1,
        }));
      }

      if (msg.type === 'offer' || msg.type === 'answer' || msg.type === 'ice-candidate') {
        // Relay to all other peers in the room
        rooms.get(currentRoom)?.forEach((peer) => {
          if (peer !== ws && peer.readyState === 1) {
            peer.send(JSON.stringify({ ...msg, from: 'peer' }));
          }
        });
      }
    });

    ws.on('close', () => {
      if (currentRoom) {
        rooms.get(currentRoom)?.delete(ws);
      }
    });
  });

  return wss;
}

module.exports = { createSignalingServer };
// signaling-server.test.js
const { WebSocket } = require('ws');
const { createSignalingServer } = require('./signaling-server');

let server;
const PORT = 9877;

beforeAll((done) => {
  server = createSignalingServer(PORT);
  server.on('listening', done);
});

afterAll((done) => server.close(done));

function connect() {
  return new Promise((resolve, reject) => {
    const ws = new WebSocket(`ws://localhost:${PORT}`);
    ws.on('open', () => resolve(ws));
    ws.on('error', reject);
  });
}

function nextMessage(ws) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => reject(new Error('Timeout')), 3000);
    ws.once('message', (data) => {
      clearTimeout(timer);
      resolve(JSON.parse(data.toString()));
    });
  });
}

test('peer receives offer relayed by signaling server', async () => {
  const peer1 = await connect();
  const peer2 = await connect();

  // Both join the same room
  peer1.send(JSON.stringify({ type: 'join', room: 'test-room-1' }));
  await nextMessage(peer1); // joined

  peer2.send(JSON.stringify({ type: 'join', room: 'test-room-1' }));
  await nextMessage(peer2); // joined

  // peer1 sends an offer
  const fakeOffer = { type: 'offer', sdp: 'v=0\r\no=...' };
  peer1.send(JSON.stringify(fakeOffer));

  // peer2 should receive it
  const received = await nextMessage(peer2);
  expect(received.type).toBe('offer');
  expect(received.sdp).toBe(fakeOffer.sdp);
  expect(received.from).toBe('peer');

  peer1.close();
  peer2.close();
});

test('peer in different room does not receive offer', async () => {
  const peer1 = await connect();
  const peer2 = await connect();

  peer1.send(JSON.stringify({ type: 'join', room: 'room-A' }));
  await nextMessage(peer1);

  peer2.send(JSON.stringify({ type: 'join', room: 'room-B' }));
  await nextMessage(peer2);

  peer1.send(JSON.stringify({ type: 'offer', sdp: 'v=0' }));

  // peer2 should NOT receive anything
  await expect(
    Promise.race([
      nextMessage(peer2),
      new Promise((_, reject) => setTimeout(() => reject(new Error('No message')), 500)),
    ])
  ).rejects.toThrow('No message');

  peer1.close();
  peer2.close();
});

Mocking RTCPeerConnection

Testing client-side WebRTC logic requires mocking RTCPeerConnection. The real API is unavailable in Node.js, and even in browser environments you don't want actual media negotiation in unit tests.

// __mocks__/rtc.js
class MockRTCPeerConnection {
  constructor(config) {
    this.config = config;
    this.localDescription = null;
    this.remoteDescription = null;
    this.connectionState = 'new';
    this.iceConnectionState = 'new';
    this._eventHandlers = {};
    this._dataChannels = [];
  }

  async createOffer() {
    return { type: 'offer', sdp: 'mock-offer-sdp' };
  }

  async createAnswer() {
    return { type: 'answer', sdp: 'mock-answer-sdp' };
  }

  async setLocalDescription(desc) {
    this.localDescription = desc;
    // Simulate ICE gathering
    setTimeout(() => {
      this._trigger('icecandidate', {
        candidate: { candidate: 'mock-candidate', sdpMid: '0', sdpMLineIndex: 0 },
      });
      this._trigger('icecandidate', { candidate: null }); // gathering complete
    }, 10);
  }

  async setRemoteDescription(desc) {
    this.remoteDescription = desc;
  }

  async addIceCandidate(candidate) {
    // No-op in mock
  }

  createDataChannel(label, options) {
    const channel = new MockRTCDataChannel(label);
    this._dataChannels.push(channel);
    return channel;
  }

  addEventListener(event, handler) {
    if (!this._eventHandlers[event]) this._eventHandlers[event] = [];
    this._eventHandlers[event].push(handler);
  }

  removeEventListener(event, handler) {
    if (this._eventHandlers[event]) {
      this._eventHandlers[event] = this._eventHandlers[event].filter(h => h !== handler);
    }
  }

  _trigger(event, data) {
    this._eventHandlers[event]?.forEach(h => h(data));
    const prop = `on${event}`;
    if (this[prop]) this[prop](data);
  }

  close() {
    this.connectionState = 'closed';
  }
}

class MockRTCDataChannel {
  constructor(label) {
    this.label = label;
    this.readyState = 'open';
    this._messages = [];
  }

  send(data) {
    this._messages.push(data);
  }
}

module.exports = { MockRTCPeerConnection, MockRTCDataChannel };

Now test your WebRTC client logic:

// webrtc-client.test.js
const { MockRTCPeerConnection } = require('./__mocks__/rtc');
const { WebRTCClient } = require('./webrtc-client');

// Inject mock
global.RTCPeerConnection = MockRTCPeerConnection;

test('initiates offer/answer exchange through signaling', async () => {
  const signalingMessages = [];
  const mockSignaling = {
    send: (msg) => signalingMessages.push(JSON.parse(msg)),
  };

  const client = new WebRTCClient(mockSignaling);
  await client.call('room-xyz');

  // Should have created and sent an offer
  const offerMsg = signalingMessages.find(m => m.type === 'offer');
  expect(offerMsg).toBeDefined();
  expect(offerMsg.sdp).toBe('mock-offer-sdp');
});

test('sends ICE candidates through signaling after setLocalDescription', async () => {
  const signalingMessages = [];
  const mockSignaling = {
    send: (msg) => signalingMessages.push(JSON.parse(msg)),
  };

  const client = new WebRTCClient(mockSignaling);
  await client.call('room-xyz');

  // Wait for mock ICE events (10ms timeout in mock)
  await new Promise(r => setTimeout(r, 50));

  const iceMsgs = signalingMessages.filter(m => m.type === 'ice-candidate');
  expect(iceMsgs.length).toBeGreaterThan(0);
  expect(iceMsgs[0].candidate.candidate).toBe('mock-candidate');
});

Integration Testing with wrtc

For closer-to-real integration tests in Node.js, use the wrtc package:

npm install --save-dev wrtc

wrtc implements the WebRTC APIs in Node, allowing actual peer connections without a browser:

const wrtc = require('wrtc');
const { createSignalingServer } = require('./signaling-server');
const { WebSocket } = require('ws');

test('two peers establish data channel connection', async () => {
  const PORT = 9878;
  const server = createSignalingServer(PORT);
  await new Promise(r => server.on('listening', r));

  const peer1 = new wrtc.RTCPeerConnection({ iceServers: [] });
  const peer2 = new wrtc.RTCPeerConnection({ iceServers: [] });

  const ws1 = new WebSocket(`ws://localhost:${PORT}`);
  const ws2 = new WebSocket(`ws://localhost:${PORT}`);

  await Promise.all([
    new Promise(r => ws1.on('open', r)),
    new Promise(r => ws2.on('open', r)),
  ]);

  ws1.send(JSON.stringify({ type: 'join', room: 'integration-test' }));
  ws2.send(JSON.stringify({ type: 'join', room: 'integration-test' }));

  // Wire signaling
  peer1.onicecandidate = (e) => {
    if (e.candidate) ws1.send(JSON.stringify({ type: 'ice-candidate', candidate: e.candidate }));
  };
  peer2.onicecandidate = (e) => {
    if (e.candidate) ws2.send(JSON.stringify({ type: 'ice-candidate', candidate: e.candidate }));
  };

  ws2.on('message', async (data) => {
    const msg = JSON.parse(data.toString());
    if (msg.type === 'offer') {
      await peer2.setRemoteDescription(msg);
      const answer = await peer2.createAnswer();
      await peer2.setLocalDescription(answer);
      ws2.send(JSON.stringify({ type: 'answer', ...answer }));
    }
    if (msg.type === 'ice-candidate') {
      await peer2.addIceCandidate(msg.candidate);
    }
  });

  // Create data channel and initiate offer
  const channel = peer1.createDataChannel('test');
  const offer = await peer1.createOffer();
  await peer1.setLocalDescription(offer);
  ws1.send(JSON.stringify({ type: 'offer', ...offer }));

  // Wait for connection
  await new Promise((resolve) => {
    channel.onopen = resolve;
  });

  expect(channel.readyState).toBe('open');

  peer1.close();
  peer2.close();
  ws1.close();
  ws2.close();
  await new Promise(r => server.close(r));
}, 15000);

Testing Network Conditions

Real-world WebRTC failures often involve packet loss, high latency, and bandwidth constraints. The Chrome DevTools Network Throttling API can simulate these conditions in Playwright tests:

// playwright-webrtc.test.js
const { chromium } = require('playwright');

test('video call degrades gracefully under packet loss', async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext();

  // Enable network emulation
  const cdp = await context.newCDPSession(await context.newPage());
  await cdp.send('Network.emulateNetworkConditions', {
    offline: false,
    latency: 150,      // 150ms RTT
    downloadThroughput: 500 * 1024 / 8,  // 500kbps
    uploadThroughput: 500 * 1024 / 8,
  });

  // Navigate and conduct the WebRTC test
  const page = await context.newPage();
  await page.goto('https://your-app.example.com/call');
  await page.click('[data-testid="start-call"]');

  // Assert that the app shows a "poor connection" indicator
  await expect(page.locator('[data-testid="connection-quality"]')).toHaveText('Poor');

  await browser.close();
});

For systematic testing across multiple network profiles and browser combinations, HelpMeTest's cloud-based browser execution lets you run these scenarios on real Chrome and Firefox instances without managing your own browser infrastructure.

What to Test and What to Accept

Be realistic about what automated tests can cover:

Automatable:

  • Signaling server relay logic
  • Client-side state machine (offer/answer flow)
  • ICE candidate handling
  • DataChannel message passing
  • Application behavior under simulated network degradation

Requires manual/specialized tooling:

  • Audio/video quality (requires perceptual quality metrics)
  • Cross-network NAT traversal (requires actual separate networks)
  • Mobile browser compatibility
  • Hardware codec compatibility

Focus automated tests on the signaling layer and application logic. For the media layer, use specialized tools like Selenium's WebDriver BiDi media commands or Playwright's getFakeCameraVideoTrack for synthetic streams.

Summary

WebRTC testing is layered:

  1. Test your signaling server as a WebSocket server — it's the most straightforward layer
  2. Mock RTCPeerConnection for unit tests of your client state machine
  3. Use wrtc for Node.js integration tests of the full offer/answer/ICE flow
  4. Use Playwright + CDP for browser-level tests with network simulation

The goal isn't to test WebRTC itself — the browser handles that. The goal is to test your application's WebRTC usage: that your signaling is correct, your state machine handles errors, and your UI reflects connection state accurately.

Read more

Start now free