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.
- Example: Loading a HTML file
- Example: HTML file with script tag
- JSDOM's
runScripts
option - JSDOM's
resources
option - JSDOM Issue & answers about listening for the load event before accessing the JSDOM object
- Stack Overflow answer about listening for the load event and resolving a promise
In your tests, trigger the events you need using JavaScript's.dispatchEvent()