单元测试Observable订阅中引发的错误

时间:2020-05-25 15:36:27

标签: angular unit-testing karma-jasmine

在Angular应用程序中,我在Error中扔了Observable.subscribe()。但是,在我的单元测试中,错误并没有被发现,而只是冒出气泡而使测试失败。

这是我要测试的代码:

  ngOnInit() {
    this.activatedRoute.queryParamMap
    .subscribe(params => {
      this.productType = params.get('auftragTyp');
      if (!this.productType) {
        this.router.navigate(['/conversations']);
        throw new Error(`Missing product type!`);
      }
    });
  }

这里是单元测试:

describe('TaskComponent', () => {
  let component: TaskComponent;
  let fixture: ComponentFixture<TaskComponent>;
  let activatedRouteMock = { queryParamMap: new Subject<any>() };

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [TaskComponent],
      imports: [
        RouterTestingModule,
        BrowserAnimationsModule
      ],
      providers: [
        { provide: ActivatedRoute, useValue: activatedRouteMock}
      ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TaskComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should NOT navigate to Conversations', fakeAsync(() => {
    activatedRouteMock.queryParamMap.next(convertToParamMap({
      order: 'tool',
      partnerNr: '123'
    }));

    tick(); // wait for resolution
    fixture.detectChanges();

    expect(routerMock.navigate).toHaveBeenCalledWith(['/conversations']);

    expect(component.ngOnInit).toThrowError('Missing product type!');
  }));
});

我使用fakeAsynctick(),因为我需要在测试中模拟来自ActivateRoute的不同的queryParams,因此使用Subject然后使用fixture.detectChanges()发出新的查询参数。


更新

尝试使用throwError,但结果相同:

ngOnInit() {
    this.activatedRoute.queryParamMap
    .pipe(
      map((p: ParamMap) => {
        if (p.get('auftragTyp') !== null) {
          return p;
        } else {
          this.router.navigate(['/conversations']);
          throw new Error('Missing product type!');
        }
      })
    )
    .subscribe({
      next: (params: ParamMap) => {
        this.productType = params.get('auftragTyp');
        // ...
      }
    });
  }

0 个答案:

没有答案