javascript / intermediate
Snippet
Spying on Component Method Invocations and DOM Events in Jasmine
Unit testing Angular components involves creating a test bed fixture, querying DOM elements through debug elements, and tracking method execution with Jasmine spies. This allows verifying that user interactions in the template reliably invoke the expected TypeScript class methods.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { ComponentFixture, TestBed } from '@angular/core/testing';import { By } from '@angular/platform-browser';import { CounterComponent } from './counter.component';describe('CounterComponent', () => {let component: CounterComponent;let fixture: ComponentFixture<CounterComponent>;beforeEach(async () => {await TestBed.configureTestingModule({imports: [CounterComponent]}).compileComponents();fixture = TestBed.createComponent(CounterComponent);component = fixture.componentInstance;fixture.detectChanges();});it('should trigger increment method upon button click', () => {spyOn(component, 'increment');const buttonElement = fixture.debugElement.query(By.css('button.increment-btn'));buttonElement.triggerEventHandler('click', null);expect(component.increment).toHaveBeenCalledTimes(1);});});
angular
Breakdown
1
await TestBed.configureTestingModule({ imports: [CounterComponent] }).compileComponents();
Initializes the Angular testing module environment and compiles standalone component templates.
2
spyOn(component, 'increment');
Installs a Jasmine spy on the component's increment method to track call count and passed arguments.
3
const buttonElement = fixture.debugElement.query(By.css('button.increment-btn'));
Locates the target DOM button using Angular's By.css locator strategy.
4
buttonElement.triggerEventHandler('click', null);
Simulates a native click event dispatched from the queried DOM element.