【发布时间】:2019-03-06 14:01:04
【问题描述】:
在我的 Angular 组件中,我使用以下代码创建了两个可观察对象
this.navigationEnd = this.router.events.subscribe((event: any) => {
// do some stuff
});
if (this.activeRoute.firstChild) {
this.activeRouteChild = this.activeRoute.firstChild.params.subscribe((routeParams) => {
// do some stuff
});
}
如您所见,我订阅了 activeRoute 和 router.events。由于我是一名优秀的程序员,我确保在使用 ngOnDestroy 销毁组件时取消订阅两者
public ngOnDestroy(): void {
if (this.navigationEnd) {
this.navigationEnd.unsubscribe();
}
if (this.activeRouteChild) {
this.activeRouteChild.unsubscribe();
}
}
现在这很好,但是是时候测试在销毁组件时这两个项目都取消订阅了,这是我的测试
describe('ngOnDestroy', () => {
it('should unsubscribe from navigationEnd & activeRouteChild on ngOnDestroy', () => {
// arrange
fixture.detectChanges();
// act
instance.ngOnDestroy();
// assert
expect((instance as any).navigationEnd.closed).toBeTruthy();
expect((instance as any).activeRouteChild.closed).toBeTruthy();
});
});
我像这样模拟 Router 和 ActivatedRoute:
class MockRouter {
// Router
public events = of(new NavigationEnd(1, 'url/1', 'url/1'));
public navigate = () => true;
}
class MockActivatedRoute {
public firstChild = {params: of({id: '1'})};
}
这就是我在提供者数组中声明它们的方式:
{provide: Router, useClass: MockRouter },
{provide: ActivatedRoute, useValue: MockActivatedRoute}
模拟路由器工作得很好,但是它们是 MockActivatedRoute 的一个问题,因为我认为我错误地实现了 firstChild 属性。我收到错误“TypeError: Cannot read property 'closed' of undefined” - 我的问题是如何正确模拟 ActivatedRoute 并且它是 firstChild 属性?
【问题讨论】:
标签: angular unit-testing