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

我正在用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);
        }
      });
  }

解决方案:

使 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'}];

给TA打赏
共{{data.count}}人
人已打赏
未分类

如何绘制用位图创建的FirebaseVisionFace的轮廓?[关闭]

2022-9-9 8:26:17

未分类

在Angular中使用async管道时,如何设置选择元素的空值和默认值?

2022-9-9 8:26:19

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索