javascript / intermediate
Snippet
Asserting Custom Component Output Event Emitters in Angular Component Tests
When unit testing Angular components, you often need to verify that user interactions on DOM elements trigger corresponding @Output() EventEmitter emissions. By subscribing to the EventEmitter directly in the test spec and triggering synthetic events via fixture.debugElement, you can capture emitted values and assert both the payload and invocation count.
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
28
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 emit the updated count value when the increment button is clicked', () => {const emittedValues: number[] = [];component.countChange.subscribe((val: number) => emittedValues.push(val));const incrementButton = fixture.debugElement.query(By.css('[data-testid="btn-inc"]'));incrementButton.triggerEventHandler('click', null);expect(emittedValues).toEqual([1]);});});
angular
Breakdown
1
fixture = TestBed.createComponent(CounterComponent);
Creates an instance of the component test fixture containing both the class instance and DOM elements.
2
component.countChange.subscribe((val: number) => emittedValues.push(val));
Subscribes directly to the component's output event emitter to record all payloads emitted during the test.
3
const incrementButton = fixture.debugElement.query(By.css('[data-testid="btn-inc"]'));
Queries the fixture's debug DOM tree using a CSS test identifier selector.
4
incrementButton.triggerEventHandler('click', null);
Dispatches a click event handler on the debug element without relying on native browser event cycles.
5
expect(emittedValues).toEqual([1]);
Asserts that the captured output values array matches the expected state update.