Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 30 ยท Projects

Project: Test an Event System

Test a small event emitter with Jest: spies on listeners, once and off, call order, errors inside listeners and async ordering, with runnable stand-ins.

An event emitter is a classic testing exercise because its behavior is almost entirely about who gets called, with what, in which order. That is exactly what mock functions record. In this project you will test a small Emitter class: subscribing, unsubscribing, one-time listeners, ordering, a listener that throws, and an async variant where order depends on promises.

The Jest code is read-only, since Jest does not run on this site. The runnable examples use a tiny hand-made spy() function and Node's assert; they are stand-ins that behave like jest.fn() for the features used here. If you need a refresher, see Mock Functions with jest.fn.

Behaviors to pin down

Delivery Every listener gets the arguments.
once Called a single time, then removed.
off A removed listener hears nothing.
Errors One bad listener must not silence the rest.

Spies are the natural tool for all four.

1 / 2

The class under test

JavaScript
// emitter.js
export class Emitter {
  #listeners = new Map();

  on(event, listener) {
    const list = this.#listeners.get(event) ?? [];
    this.#listeners.set(event, [...list, listener]);
    return () => this.off(event, listener); // an unsubscribe function
  }

  once(event, listener) {
    const wrapper = (...args) => {
      this.off(event, wrapper);
      return listener(...args);
    };
    return this.on(event, wrapper);
  }

  off(event, listener) {
    const list = this.#listeners.get(event) ?? [];
    this.#listeners.set(event, list.filter((item) => item !== listener));
  }

  emit(event, ...args) {
    const errors = [];
    for (const listener of this.#listeners.get(event) ?? []) {
      try {
        listener(...args);
      } catch (error) {
        errors.push(error);
      }
    }
    if (errors.length > 0) throw new AggregateError(errors, "listener failed");
  }

  async emitAsync(event, ...args) {
    for (const listener of this.#listeners.get(event) ?? []) {
      await listener(...args);
    }
  }
}

Two design choices make the class testable. on returns an unsubscribe function, so a test never needs to hold on to the wrapper. And emit reads the list of listeners as it was when the loop started, because on and off create a new array each time instead of changing the old one. That detail matters when a listener removes itself during the emit, which is exactly what once does.

Listing the behaviors

Write what you will assert, grouped by area:

  • Delivery: all listeners for an event are called with the emitted arguments; listeners for other events are not.
  • Order: listeners run in the order they were added.
  • once: called once even after two emits.
  • off / unsubscribe: a removed listener is not called.
  • Errors: a throwing listener does not stop the others; emit reports the failure afterwards.

A Jest version of the first group would look like this:

JavaScript
import { Emitter } from "./emitter.js";

describe("Emitter", () => {
  let emitter;
  beforeEach(() => {
    emitter = new Emitter();
  });

  test("passes arguments to every listener of that event", () => {
    const a = jest.fn();
    const b = jest.fn();
    const other = jest.fn();
    emitter.on("save", a);
    emitter.on("save", b);
    emitter.on("delete", other);

    emitter.emit("save", 42, "draft");

    expect(a).toHaveBeenCalledWith(42, "draft");
    expect(b).toHaveBeenCalledTimes(1);
    expect(other).not.toHaveBeenCalled();
  });
});

Notice beforeEach creating a fresh emitter. A shared emitter would leak listeners from one test into the next, a problem described in Test Isolation and Shared State.

Testing call order across spies

Each mock records its own calls, but toHaveBeenCalledBefore is not part of core Jest. A reliable way to check order between listeners is a shared log that every listener appends to:

JavaScript
test("calls listeners in the order they were added", () => {
  const log = [];
  emitter.on("tick", () => log.push("first"));
  emitter.on("tick", () => log.push("second"));

  emitter.emit("tick");

  expect(log).toEqual(["first", "second"]);
});

Jest also records mock.invocationCallOrder on every mock, a number that increases across all mocks, so a.mock.invocationCallOrder[0] < b.mock.invocationCallOrder[0] works too. The shared log is easier to read when something fails.

Stand-in 1: the synchronous suite

The runnable version replaces jest.fn() with a small spy() that records calls. It is a stand-in, not Jest's implementation.

Node.js Stand-in: testing delivery, once, off and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last test is the one that earns its keep. Without the try/catch inside emit, a failing first listener would silently skip the second, and nothing in the happy-path tests would have noticed.

Async ordering

emitAsync awaits each listener before starting the next. A test must prove both the order and that the next listener really waited. Use a shared log with start and end markers:

JavaScript
test("emitAsync waits for each listener", async () => {
  const log = [];
  emitter.on("load", async () => {
    log.push("a:start");
    await Promise.resolve();
    log.push("a:end");
  });
  emitter.on("load", async () => log.push("b:start"));

  await emitter.emitAsync("load");

  expect(log).toEqual(["a:start", "a:end", "b:start"]);
});

If emitAsync forgot the await, the log would read ["a:start", "b:start", "a:end"] and this test would fail. Remember the forgotten-await trap from Testing Promises and Async/Await: the test itself must also await the call, or it finishes before anything is logged.

Stand-in 2: sequential versus parallel

This stand-in compares the sequential loop with a parallel version, so you can see how a log reveals the difference.

Node.js Stand-in: a log shows async order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Whichever you choose for your emitter, write the exact expected log into the test. It documents the contract: a later change from sequential to parallel becomes a visible, intentional test edit instead of a surprise.

Ideas to extend

  • Assert that emit returns nothing when there are no listeners (no throw).
  • Test that removing a listener during an emit does not affect the current round.
  • Add a listenerCount(event) method and test it after on, once and off.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use a fresh Emitter in beforeEach?

    A shared instance keeps its listeners between tests, which creates order-dependent failures.
  2. 2. A listener throws inside emit. Which behavior does the lesson's class guarantee?

    emit collects errors in a try/catch, calls every listener, and then reports all failures together.
  3. 3. What is a reliable way to assert call order across several spies?

    A single ordered log makes the sequence explicit and produces a readable diff when it breaks.
  4. 4. In an async test of emitAsync, what happens if the test forgets to await the call?

    Without await, the test function returns immediately, so the assertions run too early or never run at all.

Summary

  • Event code is about calls: who was called, with which arguments, how often and in what order.
  • Spies record deliveries; a shared log is the clearest way to prove ordering.
  • Test once and unsubscribe by emitting twice and counting calls.
  • Test failure isolation: one throwing listener must not hide the others.
  • For async emitters, write the exact expected log with start and end markers, and always await the emit in the test.

Next, move to validation logic with many small rules in Project: Test a Form Validator.