• 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
2 years ago

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

3
Dwayne
Dwayne
Author
2 years 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)
}
})
“`

1
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?

44
Anamika Singh
Anamika Singh
10 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

  • I Joined Truth Social Using a VPN and Editing Some HTML to Bypass the Phone Verification
  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • Thoughts on the Flipper Zero
  • Waiting for an Element to Exist With JavaScript
  • How To Paginate An Array In Javascript
  • How To Mock uuid In Jest
  • How To Decompile And Compile Android APK's On A Mac Using Apktool
  • How To Get Last 4 Digits of A Credit Card Number in Javascript
  • Wild Natural Deodorant Review

Recent Comments

  • CJ on Microsoft Modern Wireless Headset Review
  • Dwayne on Microsoft Modern Wireless Headset Review
  • CJ on Microsoft Modern Wireless Headset Review
  • john on Microsoft Modern Wireless Headset Review
  • Dwayne on Why You Should Be Using globalThis Instead of Window In Your Javascript Code

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz