Evan Cordulack

Using JSDOM to Test Code With Event Listeners

April 30, 2020

If you are writing tests for a React application, you can use Enzyme's simulate() to trigger an event and make sure that your component responds appropriately. When you are working with an application written in plain/vanilla JavaScript, you can use JSDOM to test how your it responds to various events.

Example: Application with Event Listeners and JSDOM tests

Use JSDOM's fromFile() to load a html file that includes a script tag that loads the bundled version of your code under test. However, JSDOM won't load your scripts by default and , so you need to set the { resources: 'usable', runScripts: 'dangerously', } options. In your test code, you will also need to make sure you wait for JSDOM to finish loading the resources, so use an event listener in your test code to tell your test runner when everything is ready.

In your tests, trigger the events you need using JavaScript's.dispatchEvent()