簡體   English   中英

Angular 5和Jasmine-如何模擬activeRoute.firstChild以測試ngOnDestroy上的退訂

[英]Angular 5 & Jasmine - How to mock activeRoute.firstChild to test unsubscribe on ngOnDestroy

在我的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'})};
}

這就是我在providers數組中聲明它們的方式:

{provide: Router, useClass: MockRouter },
{provide: ActivatedRoute, useValue: MockActivatedRoute}

模擬路由器工作得很好,但是它們是MockActivatedRoute的問題,因為我認為我錯誤地實現了firstChild屬性。 我收到錯誤消息“ TypeError:無法讀取未定義的'closed'屬性”-我的問題是如何正確模擬ActivatedRoute及其firstChild屬性?

您不需要類來模擬子路線,只需在測試中通過調用帶有必要參數的Navigation即可導航到該子路線。 您可以先測試您的應用程序是否未進行路由(檢查您的路由路徑是否為初始路由),然后通過檢查導航后路由是否發生更改(檢查您的路徑是否為導航路徑)來進行驗證。 然后,您可以檢查此后是否取消訂閱組件。

注意 :就測試而言,我發現測試您未編寫的API並不經常有用,除非您為它們做貢獻。 unsubscribe()可以正常工作,我們知道這是因為Angular的貢獻者已經為此編寫了測試。 自己進行測試雖然不錯,但通常已浪費時間,因為它已經在Angular源代碼中進行了測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM