Angular。如何在Angular单元测试中使用路由器?

问题描述 投票:0回答:1

我正在用angular写一个测试用例。我写了一个条件,如果 res.length === 1 重定向到详情页。(this.router.navigate(['details', id])). 我得到的是 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);
        }
      });
  }
angular unit-testing karma-jasmine router
1个回答
1
投票

使 RouterStore 组件中的public和try。

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]);
});

同样覆盖 else改为 const response = [{id: 'val'}];


0
投票

把这个东西添加到你的imports中。

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

以后在你的测试用例中:你可以监视Router的 "Navigate",并使用它重定向到imports中提到的任何组件。

spyOn(Router,"navigate").and.callthrough();
router.navigate([/path1]);
© www.soinside.com 2019 - 2024. All rights reserved.