如何使用 ngx-auto-unsubscribe 测试我是否已取消订阅?
How to test that I have unsubscribed using ngx-auto-unsubscribe?
有什么方法可以让我编写单元测试来检查我是否已成功取消订阅 Observable
订阅?
我正在使用 ngx-auto-unsubscribe
。
示例:
@AutoUnsubscribe()
@Component
// Template and style urls
export class MyComp implements OnInit, OnDestroy {
mySub: Subscription;
constructor(private myService: MyService) { }
ngOnInit() {
this.myService.doSomething.subscribe(res => {
console.log(res);
})
}
ngOnDestroy() {
// Only used for AOT (ahead of time) compilation
}
}
是的,有办法(尽管我认为没有必要测试它)。
我不会为您编写整个测试,但逻辑如下:
- 在您的测试中创建一个父组件(让我们称之为
MockComponent
),使用基本 ngIf
条件来显示您的 MyComp
或不显示
- 使用您构建的另一个可观察对象模拟您服务中的可观察对象:
.
const obsCleanUpFunction = jasmine.createSpy();
const obs$ = new Observable(observer => {
//following will be called when/if the observable if completed
return obsCleanUpFunction;
});
- 创建组件
MockComponent
,其中包含 MyComp
- 运行 要在
ngOnInit
中传递的更改检测并订阅它
- 在组件
MockComponent
上,将显示 MyComp
的条件设置为 false --> 它会被评估为 false 的 ngIf
销毁
- 期待茉莉花间谍
toHaveBeenCalled
有什么方法可以让我编写单元测试来检查我是否已成功取消订阅 Observable
订阅?
我正在使用 ngx-auto-unsubscribe
。
示例:
@AutoUnsubscribe()
@Component
// Template and style urls
export class MyComp implements OnInit, OnDestroy {
mySub: Subscription;
constructor(private myService: MyService) { }
ngOnInit() {
this.myService.doSomething.subscribe(res => {
console.log(res);
})
}
ngOnDestroy() {
// Only used for AOT (ahead of time) compilation
}
}
是的,有办法(尽管我认为没有必要测试它)。
我不会为您编写整个测试,但逻辑如下:
- 在您的测试中创建一个父组件(让我们称之为
MockComponent
),使用基本ngIf
条件来显示您的MyComp
或不显示 - 使用您构建的另一个可观察对象模拟您服务中的可观察对象:
.
const obsCleanUpFunction = jasmine.createSpy();
const obs$ = new Observable(observer => {
//following will be called when/if the observable if completed
return obsCleanUpFunction;
});
- 创建组件
MockComponent
,其中包含MyComp
- 运行 要在
ngOnInit
中传递的更改检测并订阅它 - 在组件
MockComponent
上,将显示MyComp
的条件设置为 false --> 它会被评估为 false 的 - 期待茉莉花间谍
toHaveBeenCalled
ngIf
销毁