我目前正在为一些较旧的 Angular 代码编写单元测试,这些代码不是我编写的,也无法更改。
这是一个简化的示例:
export class SomeServiceComponent implements OnDestroy {
private someSubscription!: Subscription;
constructor(public someService: SomeService) {
this.someSubscription = this.someService.getSub$('data').subscribe(
response => {
...
}
)
}
ngOnDestroy(): void {
this.someSubscription?.unsubscribe();
}
}
}
代码工作正常,我的单元测试可以执行组件中的所有代码,除了 ngOnDestroy 执行时 someSubscription 为 null(或未定义)的一种情况。
我无法在单元测试中显式地将 someSubscription 设置为 null 或 undefined - 这两个值都不兼容 - 那么是否有另一种方法来编写单元测试来执行 ngOnDestroy 中的问号情况?
我们可以使用下面的属性访问来设置私有变量的值!
desc("ngOnDestroy Tests", () => {
it("should unsubscribe the subscription", () => {
component['someSubscription'] = {
unsubscribe: () => {},
};
spyOn<any>(component['someSubscription'], 'unsubscribe');
component.ngOnDestroy();
expect(component['someSubscription'].unsubscribe).toHaveBeenCalled();
});
})