簡體   English   中英

Angular:如何在 angular 單元測試中使用路由器

[英]Angular: How to use router in angular unit testing

我正在 angular 中編寫一個測試用例。 如果res.length === 1重定向到詳細信息頁面,我已經寫了一個條件。 this.router.navigate(['details', id]) )。 我從 object 的第一個數組中獲取id作為const id = res[0].id 這兩行都沒有包含在我的代碼覆蓋范圍內。 誰能讓我知道我在哪里犯了錯誤?

我正在Expected spy navigate to have been called with [ [ '/product-details', 'SAAASD0001' ] ] but it was never called.

app.component.spec.ts

let router = {navigate: jasmine.createSpy('navigate')};
TestBed.configureTestingModule({
  imports: [RouterTestingModule],
  providers: [
    { provide: Router, useValue: router }
  ]
})
it('should take data from store', () => {
  const mockData = [
      {
        id: '123',
        name: 'Stackoverlow',
      }
  ]
  expect(component.getList).toEqual(mockData);

  const productId = mockData[0].id;
  expect(router.navigate).toHaveBeenCalledWith(['/details', id]);
});

app.component.ts

  getList() {
    this.store
      .select('content', 'catalogue')
      .pipe(takeUntil(this.onDestroy$))
      .subscribe((res) => {
        Iif (res.length === 1) {
          // this line doesn't cover
          const id = res[0].id;
          // this line doesn't cover
          this.router.navigate(['details', id]);
        } else {
          this.list = category(res);
        }
      });
  }

在組件中公開RouterStore並嘗試:

TestBed.configureTestingModule({
  imports: [RouterTestingModule],
  providers: [Router,Store ]
})

it('should take data from store', () => {
  const response = [{id: 'val'}];
  spyOn(component.store,"select").and.returnValue(of(response));
  spyOn(component.router,"navigate").and.callThrough();
  component.getList();
  expect(router.navigate).toHaveBeenCalledWith(['/details', response[0].id]);
});

同樣通過更改const response = [{id: 'val'}];來覆蓋else部分

將此東西添加到您的導入中:

 RouterTestingModule.withRoutes([
          { path: 'path1', component: TestComponent1},
          { path: 'home', component: DashboardComponent }
        ]),

稍后在您的測試用例中:您可以監視路由器的“導航”並將其用於重定向到導入中提到的任何組件。

spyOn(Router,"navigate").and.callthrough();
router.navigate([/path1]);

暫無
暫無

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

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