首页 > 解决方案 > 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();

但这对我来说似乎很不雅。有没有更好的方法来确保订阅被解雇?

非常感谢您的帮助

标签: angularunit-testingrxjsngrx

解决方案


推荐阅读