Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How do I mock a DOM element in Jest for testing event listeners?
Asked on Jan 06, 2026
Answer
To mock a DOM element in Jest for testing event listeners, you can use Jest's built-in functions to simulate the DOM environment and attach event listeners to mock elements.
<!-- BEGIN COPY / PASTE -->
// Import necessary functions from Jest
const { JSDOM } = require('jsdom');
// Create a mock DOM environment
const dom = new JSDOM('<!DOCTYPE html><html><body><button id="myButton">Click me</button></body></html>');
const document = dom.window.document;
// Select the button element
const button = document.getElementById('myButton');
// Mock a click event listener
const handleClick = jest.fn();
button.addEventListener('click', handleClick);
// Simulate a click event
button.click();
// Test if the event listener was called
expect(handleClick).toHaveBeenCalled();
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The code uses JSDOM to create a mock DOM environment for testing.
- A button element is selected using "getElementById".
- An event listener is added to the button, and "jest.fn()" is used to mock the function.
- The "click" method simulates a click event on the button.
- "expect(handleClick).toHaveBeenCalled()" checks if the event listener was triggered.
Recommended Links:
