首页 > 解决方案 > 如何测试 rxjs 链中的函数

问题描述

我正在尝试测试回调在关闭后发生mat-dialog。我的代码显示为 rxjs 链,我需要测试该链中的一些函数

这是带有 Angular 材质的 Angular 7

测试代码


deleteProject() {
    this.dialog.open(DeleteProjectDialogComponent, {
      data: {
        project: this.project
      },
      minWidth: MIN_DIALOG_WIDTH
    })
      .afterClosed()
      .pipe(
        take(1),
        filter(Boolean),
        switchMap(() => this.apiProjects.deleteProject(this.project.id)), // <= need to test this call of this function
        withLatestFrom(this.translate.get('PROJECT.WAS_DELETED')),
        tap({
          next: ([res, translation]) => {
            this.utils.storage.clearProject();
            this.utils.navigation.goToAuthPage();
            this.snackBar.open(translation, 'OK', {
              duration: SNACK_BAR_DURATION
            });
          },
          error: res => {
            const {error} = res;
            if (res.status === 400) {
              const {name, project} = error;
              if (project) {
                this.showError(error.project);
              }
            }
          }
        })
      ).subscribe();
  }

我的测试


it('should call api after delete project', () => {

    const spyApi = spyOn(apiProject, 'deleteProject');
    spyOn(dialog, 'open').and.returnValue({
      afterClosed: () => of(true)
    });

    component.deleteProject();

    expect(spyApi).toHaveBeenCalled(); // <= failed with Error: Expected spy deleteProject to have been called.
  });

标签: angulartestingdialogangular-material

解决方案


推荐阅读