How would you test that clicking a button in a component triggers the expected behavior?
Short answer
You find the button element in the rendered component's DOM, simulate a click event on it using dispatchEvent, run change detection to let Angular process the resulting update, and then check that the expected outcome, such as an updated property or displayed text, actually…
Advertisement
AModel answer
You find the button element in the rendered component's DOM, simulate a click event on it using dispatchEvent, run change detection to let Angular process the resulting update, and then check that the expected outcome, such as an updated property or displayed text, actually occurred.
const button = fixture.nativeElement.querySelector('button');
button.click();
fixture.detectChanges();
expect(component.count).toBe(1);
expect(fixture.nativeElement.textContent).toContain('Count: 1');Real-world example
A test for a counter component simulates a real button click and verifies that both the internal count property and the actual displayed text on screen correctly update to reflect the new value.
Likely follow-ups
- Why is calling detectChanges again after the click necessary for the test to see the updated content?
- How would you test a component using the newer signal based state instead of a plain property?
Related topics