Ngrx订阅未在单元测试中触发

时间:2019-03-21 18:45:21

标签: angular unit-testing rxjs ngrx

我正在尝试编写一个单元测试,以验证在存储片上的订阅内完成了什么。当我手动尝试订阅时,而不是在单元测试中运行。

ngOnInit():void {
  this.currentPage$ = this.store.pipe(select('recipes'));

  this.activatedRoute.params.pipe(
    filter(params => 'pageId' in params),
    map(params => params.pageId),
    distinctUntilChanged(),
    takeUntil(this.unsubscribe$)
  ).subscribe(pageId => {
    this.store.dispatch(new LoadPage(pageId, 5)); 
  });


  this.store.select(getAllRecipes).pipe(skip(1)).subscribe((recipes) => {
    if (recipes !== null) {
      this.recipes = recipes['recipes'];
      this.currentPage = Number(recipes['currentPage']);
      this.totalPages = Number(recipes['totalPages']);
    };
  });
}

测试:

fit('should load all recipes of the page indicated by the value of the url param pageId', fakeAsync(() => { 
  let getRecipesSpy = spyOn(RecipeService.prototype, 'getRecipes').and.returnValue([{id: 2, title: 'trololo', description: 'htotoa'}]);    
  mockActivatedRoute.testParams = {pageId: '3'};
  //await component.store.select(getAllRecipes).subscribe();
  //tick();
  fixture.detectChanges();
  expect(getRecipesSpy).toHaveBeenCalledWith(3);
  expect(component.recipes).toEqual([{id: 2, title: 'kjhkh', description: 'hahahoho'}]);
}));

在我的代码的其他地方,我可以使用: await component.currentPage$.subscribe();

但这对我来说似乎很简单。有没有更好的方法来确保订阅被触发?

非常感谢您的帮助

0 个答案:

没有答案