test-event-listeners
Test-friendly object creator to simulate adding listeners for events.
Allows you to add event listeners on an object and fire them at will.
Great for simulating window
or document
events during tests!
No dependencies. Tiny size. Blazingly fast. Easy breezy.
Usage
import { createRegister } from "test-event-listeners";
const register = createRegister();
register.addEventListener("foo", (data) => console.log(`Got ${data}!`));
// Got bar!
register.fireEvent("foo", "bar");
This can be useful if, for example, you're manipulating a window's "click"
and "keydown"
events with Jest spies:
import { createRegister } from "test-event-listeners";
// Arrange
const register = createRegister();
const keyDownSpy = jest.fn();
register.addEventListener("keydown", keyDownSpy)
// Act
register.fireEvent("keydown");
// Assert
expect(keyDownSpy).toHaveBeenCalledTimes(1);
Usage with TypeScript
Good news: test-event-listeners is written in TypeScript!
You'll never have to worry about @types
mismatches here!
createRegister
takes two templated types:
TEventName extends string
: Event names that may be fired.TListener extends Function
: Type of functions stored as listeners.
const register = createRegister<"keydown", jasmine.Spy>();