如何为含EventEmitter与subscribe的Angular代码编写单元测试用例
Angular组件单元测试用例编写(针对EventEmitter与CustomService订阅逻辑)
首先明确待测试的完整组件代码:
import { EventEmitter, OnInit } from '@angular/core'; import { CustomService } from '@service/customService'; export class YourComponent implements OnInit { @Output() passVal = new EventEmitter<any>(); constructor(private customService: CustomService) {} ngOnInit(): void { this.callBackEvent(); } callBackEvent() { this.customService.getEvent.subscribe((val: boolean) => { if (val) { this.passVal.emit(true); } }); } }
编写单元测试用例
我们需要隔离真实依赖(Mock CustomService),针对三个核心逻辑场景编写测试:
1. 测试文件基础结构与Mock服务定义
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { YourComponent } from './your.component'; import { CustomService } from '@service/customService'; import { Subject } from 'rxjs'; // Mock CustomService,完全控制事件发射逻辑 class MockCustomService { private getEventSubject = new Subject<boolean>(); getEvent = this.getEventSubject.asObservable(); // 提供测试专用的事件发射方法 emitGetEvent(value: boolean) { this.getEventSubject.next(value); } } describe('YourComponent', () => { let component: YourComponent; let fixture: ComponentFixture<YourComponent>; let customService: MockCustomService; let passValEmitSpy: jasmine.Spy; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [YourComponent], providers: [ { provide: CustomService, useClass: MockCustomService } ] }).compileComponents(); fixture = TestBed.createComponent(YourComponent); component = fixture.componentInstance; customService = TestBed.inject(CustomService) as unknown as MockCustomService; // 监听passVal的emit方法,用于后续验证调用情况 passValEmitSpy = spyOn(component.passVal, 'emit'); // 触发组件初始化,执行ngOnInit逻辑 fixture.detectChanges(); });
2. 测试场景:组件初始化时正确订阅服务事件
it('should subscribe to CustomService.getEvent when ngOnInit runs', () => { customService.emitGetEvent(true); // 通过验证passVal被触发,间接证明订阅逻辑执行成功 expect(passValEmitSpy).toHaveBeenCalledWith(true); });
3. 测试场景:服务发射true时,组件正确触发passVal
it('should emit true via passVal when CustomService emits true', () => { customService.emitGetEvent(true); expect(passValEmitSpy).toHaveBeenCalledOnceWith(true); });
4. 测试场景:服务发射false时,组件不触发passVal
it('should NOT trigger passVal when CustomService emits false', () => { customService.emitGetEvent(false); expect(passValEmitSpy).not.toHaveBeenCalled(); }); });
关键说明
- 使用Mock服务隔离真实依赖,避免测试受外部服务逻辑干扰
- 通过Spy跟踪
passVal.emit的调用情况,精准验证组件的输出逻辑 - 覆盖初始化订阅、条件触发、条件不触发三个核心场景,保证逻辑完整性
内容的提问来源于stack exchange,提问作者Vijay Vallatharasu
相关产品推荐
相关产品推荐

