Testing Event Listeners In Jest (Without Using A Library)

I love using Jest to unit test my Aurelia applications. Sadly, one of the most popular options for mocking event listeners and simulating events called Enzyme is targeted at React applications and to my knowledge, does not work with Aurelia or any other framework like Angular.

If you are wanting to test events registered using addEventListener there is an easy way to mock them.

describe('My Test', () => {
	let sut;
	let events = {};

	beforeEach(() => {
		sut = new Dependency();

		// Empty our events before each test case
		events = {};

		// Define the addEventListener method with a Jest mock function
		document.addEventListener = jest.fn((event, callback) => {
      		map[event] = callback;
    	});
	});

	test('Test Keypress fires callback', () => {
		// Watch the keypress callback
		jest.spyOn(sut, 'keypressCallback');

		// Fire the keypress event
		events.keypress({ key: 'Enter' });
	});
});

This approach works for a lot of other things you want to test and mock.

Leave a Reply

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