Search⌘ K
AI Features

Testing Events

Understand how to test DOM events in Angular applications by simulating user actions such as clicks and key presses. Learn to use native JavaScript event APIs and Angular's DebugElement to trigger events, manage event propagation, and verify changes after Angular's change detection. This lesson equips you with techniques to write effective event-driven unit tests for robust applications.

JavaScript DOM events

We can react to user actions by attaching event listeners to nodes in the DOM. Using the addEventListener method, we can attach one or more listeners.

When the user takes an action, such as clicking on a page element, JavaScript generates events that carry information about the user action.

Our event listeners watch for a matching event and then run a callback function to carry out a desired action.

Javascript (babel-node)
let myButton = document.querySelector('button');
myButton.addEventListener('click', () => {
console.log('My button was clicked');
});

If we want to remove that event listener later on, we can use a named function as given below:

Javascript (babel-node)
let myButton = document.querySelector('button');
function clickHandler() {
console.log('My button was clicked');
}
myButton.addEventListener('click', clickHandler());
// Later, we can remove the handler
myButton.removeEventListener('click', clickHandler());

There are many different DOM events we can listen for, including the following:

  • blur
  • click
  • dblclick
  • focus
  • keydown
  • keypress
  • keyup
  • mouseenter
  • mouseleave
  • mousemove
  • mouseover

Our event listener function addEventListener receives an event, such as click, which carries information about the event. For example, we can use it to determine the target node where the event originated:

Javascript (babel-node)
let myButton = document.querySelector('button');
myButton.addEventListener('click', event => {
console.log(event.target.nodeName); // BUTTON
});

We can also determine the key pressed using the event object as given below:

Javascript (babel-node)
window.addEventListener('keydown', event => {
if (event.key === 'x') {
console.log('X key was pressed');
}
});

Event bubbling

...