• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

Testing Event Listeners In Jest (Without Using A Library)

Jest · February 19, 2020

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) => {
      		events[event] = callback;
    	});
      
        document.removeEventListener = jest.fn((event, callback) => {
      	    delete events[event];
        });
	});

	test('Test Keypress fires callback', () => {
        // Watch the function that gets called when our event fires
        jest.spyOn(sut, 'pressed');
        
        // A method inside of our dependency that sets up event listeners
		sut.setupEvents();

		// Fire the keypress event
		events.keypress({ key: 'Enter' });
        
        // We fired an event, so this should have been called
        expect(sut.pressed).toHaveBeenCalled();
	});
});

Inside of the beforeEach we do a few bootstrapping things before we run our tests. The sut variable is actually the thing we are testing. In this instance, Dependency is a class with some methods inside of it.

We populate our object which stores our events called events when addEventListener is called, our mocked version will be used, so we replicate how this would work in the browser, except we just use an object.

Inside of our test case, we are calling a method on our class called pressed here is what the dependency might look like:

export class Dependency {
    setupEvents() {
        document.addEventListener('keypress', this.pressed.bind(this), false);
    }
  
    pressed() {
        // Called when keypress event is fired
    }
}

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

Dwayne

Leave a Reply Cancel reply

6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
James Bob
James Bob
2 years ago

Worked a treat – thank you!

2
Joe Previte
Joe Previte
1 year ago

Silly question – what is `map` supposed to be?

3
Dwayne
Dwayne
Author
1 year ago

@Joe

Not silly at all, and my apologies. The map was supposed to be `events` I have since fixed this up.

2
Elvis
Elvis
1 year ago

I don’t know why google search hardly mentions using the simplest callback method, I think the callback is the most direct and practical way to test the event

“`
q.on(‘done’, function (payload, job) {
try {
expect(q._pendingCount).toBeLessThanOrEqual(5)
const elapsed = performance.now() – start
expect(elapsed).toBeGreaterThanOrEqual(200 * Math.ceil((count + 1) / 5))
if (count++ >= 10) {
q.stop()
done()
}
} catch (err) {
q.stop()
done(err)
}
})
“`

0
Kalinda
Kalinda
1 year ago

I don’t understand this line:
sut = new Dependency();

What is it doing? Is “new Dependency()” something I would actually write in my code, or is it a placeholder?

43
Anamika Singh
Anamika Singh
8 months ago

I’m trying to do same but my eventlistener has click event and I’m getting this error TypeError: events.click is not a function. also I’m seeing you have call it with object events.keypress({ key: ‘Enter’ }); what argument will go with click ?

0

Primary Sidebar

Popular

  • Thoughts on the Flipper Zero
  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • How To Paginate An Array In Javascript
  • Waiting for an Element to Exist With JavaScript
  • Reliably waiting for network responses in Playwright
  • How To Get Last 4 Digits of A Credit Card Number in Javascript
  • How to Use Neural DSP Archetype Plugins With the Quad Cortex
  • Neural DSP Reveal Details About the Long-Awaited Quad Cortex Desktop Editor
  • Removing A Character From The Start/End of a String In Javascript

Recent Comments

  • Kevmeister68 on Start-Ups and Companies That Embrace Work From Anywhere Will Be More Likely to Survive the Coming Recession in 2023
  • kevmeister68 on What Would Get People Back Into the Office?
  • Dwayne on PHP Will Not Die
  • Dwayne on How to Create a Blockchain With TypeScript
  • kevmeister68 on PHP Will Not Die

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz