【问题标题】:Angular 5 & Jasmine - How to mock activeRoute.firstChild to test unsubscribe on ngOnDestroyAngular 5 & Jasmine - 如何模拟 activeRoute.firstChild 以在 ngOnDestroy 上测试退订
【发布时间】: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


    【解决方案1】:

    您不需要一个类来模拟子路由,只需通过使用必要的参数调用 navigate 在您的测试中导航到那里。您可以通过首先测试您的应用程序是否没有路由(检查您的路由路径是否是初始路由)然后检查您导航后路由是否更改(检查您的路径是否是您导航到的路径)来验证它。然后,您可以检查您的组件是否在此之后取消订阅。

    注意:就测试而言,我发现测试不是您编写的 API 通常没有用处,除非您为它们做出贡献。 unsubscribe() 有效,我们知道这是因为 Angular 的贡献者已经为它编写了测试。自己测试虽然不错,但通常证明是浪费时间,因为它已经在 Angular 源代码中进行了测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      相关资源
      最近更新 更多