Angular 16 introduces Signals, and this example is to show how to unit test Signal output<T>().
.ts file
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html'
})
export class MyComponent {
@Output() actionTriggered = new EventEmitter<void>();
onClick() {
this.actionTriggered.emit();
}
}
.html file
<button (click)="onClick()">Click me</button>
.spec file
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my-component.component';
import { By } from '@angular/platform-browser';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyComponent]
});
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should emit actionTriggered signal when button is clicked', () => {
// 创建一个 spy 来监听信号的调用
const signalSpy = jasmine.createSpy('signalSpy');
// 订阅信号
component.actionTriggered.subscribe(signalSpy);
// 找到按钮并触发点击事件
const button = fixture.debugElement.query(By.css('button'));
button.triggerEventHandler('click', null);
// 验证 signal 被触发
expect(signalSpy).toHaveBeenCalledTimes(1);
});
});