Testing SSE: A Practical Guide to Server-Sent Events Testing

Testing SSE: A Practical Guide to Server-Sent Events Testing

Server-Sent Events (SSE) is the underrated workhorse of real-time web: simpler than WebSockets, built on standard HTTP, natively supported in every modern browser without a library. But testing SSE comes with its own challenges — streaming responses, reconnection logic, event IDs, and the browser's EventSource API don't fit neatly into standard HTTP test patterns.

This guide covers SSE testing from unit tests through integration and browser-level validation.

How SSE Works (The Bits That Affect Testing)

An SSE response is a long-lived HTTP GET request with Content-Type: text/event-stream. The server pushes newline-delimited text frames:

data: {"type":"price","value":42.50}\n\n

id: 1234\n
event: priceUpdate\n
data: {"value":43.00}\n\n

Key protocol behaviors that your tests must cover:

  • Reconnection: If the connection drops, the browser automatically reconnects, sending Last-Event-ID header with the last received event ID
  • Retry interval: Server can set retry: 3000 to tell clients how long to wait before reconnecting
  • Named events: event: myEventType allows clients to listen for specific event types
  • Heartbeats: Many servers send : keepalive comments to prevent proxy timeouts

Testing the SSE Endpoint Directly (curl)

Before writing any code, validate the raw protocol:

curl -N -H "Accept: text/event-stream" https://your-server.example.com/events

The -N flag disables buffering so you see events as they arrive. Expected output:

data: {"type":"connected"}

id: 1
data: {"type":"update","value":42}

: keepalive

id: 2
data: {"type":"update","value":43}

Test reconnection with Last-Event-ID:

curl -N \
  -H "Accept: text/event-stream" \
  -H "Last-Event-ID: 5" \
  https://your-server.example.com/events

The server should replay events after ID 5 if it supports replay, or start from the current state.

Unit Testing the SSE Server

Here's a minimal Express SSE server to test against:

// sse-server.js
const express = require('express');

function createApp(eventStore) {
  const app = express();
  const clients = new Set();

  app.get('/events', (req, res) => {
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.flushHeaders();

    const lastId = parseInt(req.headers['last-event-id'] || '0', 10);

    // Replay missed events
    const missed = eventStore.since(lastId);
    missed.forEach((event) => {
      res.write(`id: ${event.id}\n`);
      res.write(`data: ${JSON.stringify(event.data)}\n\n`);
    });

    clients.add(res);

    req.on('close', () => {
      clients.delete(res);
    });
  });

  // Broadcast to all clients
  app.broadcast = (event) => {
    clients.forEach((res) => {
      res.write(`id: ${event.id}\n`);
      res.write(`data: ${JSON.stringify(event.data)}\n\n`);
    });
  };

  return app;
}

module.exports = { createApp };

Now test it with supertest for the connection behavior, and a custom helper for stream events:

// sse-server.test.js
const http = require('http');
const { createApp } = require('./sse-server');

class MockEventStore {
  constructor(events = []) {
    this.events = events;
  }
  since(id) {
    return this.events.filter((e) => e.id > id);
  }
}

function collectSSEEvents(url, count, timeoutMs = 5000) {
  return new Promise((resolve, reject) => {
    const events = [];
    const timer = setTimeout(() => {
      req.destroy();
      if (events.length >= count) resolve(events);
      else reject(new Error(`Timeout: received ${events.length}/${count} events`));
    }, timeoutMs);

    const req = http.get(url, {
      headers: { Accept: 'text/event-stream' },
    }, (res) => {
      let buffer = '';

      res.on('data', (chunk) => {
        buffer += chunk.toString();
        const parts = buffer.split('\n\n');
        buffer = parts.pop(); // Keep incomplete last chunk

        parts.forEach((part) => {
          const lines = part.trim().split('\n');
          const event = {};
          lines.forEach((line) => {
            if (line.startsWith('data: ')) event.data = JSON.parse(line.slice(6));
            if (line.startsWith('id: ')) event.id = parseInt(line.slice(4), 10);
            if (line.startsWith('event: ')) event.type = line.slice(7);
          });
          if (event.data) events.push(event);
        });

        if (events.length >= count) {
          clearTimeout(timer);
          req.destroy();
          resolve(events);
        }
      });
    });

    req.on('error', (err) => {
      if (err.code !== 'ECONNRESET') reject(err);
    });
  });
}

describe('SSE server', () => {
  let server;
  let app;
  let port;

  beforeEach((done) => {
    const store = new MockEventStore([
      { id: 1, data: { type: 'historical', value: 10 } },
      { id: 2, data: { type: 'historical', value: 20 } },
    ]);
    app = createApp(store);
    server = app.listen(0, () => {
      port = server.address().port;
      done();
    });
  });

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

  test('sends correct content-type header', (done) => {
    http.get(`http://localhost:${port}/events`, {
      headers: { Accept: 'text/event-stream' },
    }, (res) => {
      expect(res.headers['content-type']).toBe('text/event-stream');
      res.destroy();
      done();
    });
  });

  test('replays events after Last-Event-ID', async () => {
    const events = await collectSSEEvents(
      `http://localhost:${port}/events`,
      2
    );
    expect(events).toHaveLength(2);
    expect(events[0].data.type).toBe('historical');
    expect(events[0].id).toBe(1);
  });

  test('replays only events after Last-Event-ID', async () => {
    const events = await collectSSEEvents(
      // Pass Last-Event-ID: 1, so only event 2 should replay
      `http://localhost:${port}/events`,
      1
    );
    // Manually inject header — need a custom request
    const eventsWithHeader = await new Promise((resolve, reject) => {
      const received = [];
      const req = http.get(
        `http://localhost:${port}/events`,
        { headers: { Accept: 'text/event-stream', 'last-event-id': '1' } },
        (res) => {
          let buf = '';
          const timer = setTimeout(() => { req.destroy(); resolve(received); }, 2000);
          res.on('data', (chunk) => {
            buf += chunk.toString();
            const parts = buf.split('\n\n');
            buf = parts.pop();
            parts.forEach((part) => {
              const idLine = part.split('\n').find(l => l.startsWith('id: '));
              if (idLine) received.push(parseInt(idLine.slice(4)));
            });
          });
        }
      );
      req.on('error', reject);
    });
    expect(eventsWithHeader).toEqual([2]);
  });

  test('broadcasts to connected clients', async () => {
    const eventsPromise = collectSSEEvents(
      `http://localhost:${port}/events`,
      3 // 2 historical + 1 broadcast
    );

    // Wait for client to connect, then broadcast
    await new Promise((r) => setTimeout(r, 100));
    app.broadcast({ id: 3, data: { type: 'live', value: 99 } });

    const events = await eventsPromise;
    const liveEvent = events.find((e) => e.data.type === 'live');
    expect(liveEvent).toBeDefined();
    expect(liveEvent.data.value).toBe(99);
  });
});

Testing the Browser EventSource API

The browser's EventSource has reconnection built in, but testing it requires mocking or running a real browser.

For unit tests, mock EventSource:

// __mocks__/EventSource.js
class MockEventSource {
  constructor(url) {
    this.url = url;
    this.readyState = 0; // CONNECTING
    this._listeners = {};

    // Simulate async connection
    setTimeout(() => {
      this.readyState = 1; // OPEN
      this.onopen?.({ type: 'open' });
    }, 0);
  }

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

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

  // Test helper: simulate receiving an event
  _emit(type, data) {
    const event = { type, data, lastEventId: '' };
    this.onmessage?.(event);
    this._listeners[type]?.forEach((h) => h(event));
    this._listeners['message']?.forEach((h) => h(event));
  }

  close() {
    this.readyState = 2; // CLOSED
  }
}

MockEventSource.CONNECTING = 0;
MockEventSource.OPEN = 1;
MockEventSource.CLOSED = 2;

global.EventSource = MockEventSource;

Then test your application's SSE client code:

// price-feed.test.js
require('./__mocks__/EventSource');
const { PriceFeed } = require('./price-feed');

test('updates price on incoming event', async () => {
  const feed = new PriceFeed('/events/prices');
  const prices = [];

  feed.onPrice((price) => prices.push(price));
  await feed.connect();

  // Get access to the underlying EventSource
  feed._source._emit('message', JSON.stringify({ symbol: 'BTC', price: 50000 }));

  expect(prices).toHaveLength(1);
  expect(prices[0].symbol).toBe('BTC');
  expect(prices[0].price).toBe(50000);
});

test('closes connection on destroy', async () => {
  const feed = new PriceFeed('/events/prices');
  await feed.connect();

  feed.destroy();

  expect(feed._source.readyState).toBe(2); // CLOSED
});

Testing Reconnection Logic

SSE reconnection is handled by the browser automatically, but you should test your application's behavior when reconnection occurs (e.g., state sync, duplicate prevention):

test('does not duplicate events on reconnect', async () => {
  const feed = new PriceFeed('/events/prices');
  const prices = [];
  feed.onPrice((p) => prices.push(p));
  await feed.connect();

  // Simulate receiving event ID 5
  feed._source._emit('message', JSON.stringify({ id: 5, price: 100 }));

  // Simulate disconnection and reconnect
  feed._source.onerror?.({ type: 'error' });
  // EventSource auto-reconnects — a new EventSource would be created
  // Your app should track lastEventId to avoid re-processing

  expect(prices).toHaveLength(1); // Not 2 — no duplicate
});

End-to-End SSE Testing

For full-stack testing where the browser UI must react to SSE events, you need a real browser. HelpMeTest runs Playwright-based tests in the cloud and can handle SSE scenarios: subscribe to an event stream, trigger a server-side action, and assert the UI updated within your latency threshold — all without writing browser automation code yourself. This is particularly useful for testing live dashboards and notification systems where the timing between server event and UI update matters.

Summary

SSE testing has three distinct layers:

  1. Protocol layer: Use curl and raw HTTP clients to verify headers, event format, and replay behavior
  2. Server unit tests: Use http.get with stream parsing to collect events programmatically in Jest
  3. Client unit tests: Mock EventSource to test your application's reaction to events without a server

The most commonly missed test: reconnection with Last-Event-ID. Implement it, and then test that clients reconnecting mid-stream don't miss events or process duplicates. That's the scenario that bites in production.

Read more

Start now free