Модульное тестирование - ошибка, возникающая внутри наблюдаемой подписки - PullRequest
0 голосов
/ 25 мая 2020

В приложении 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!');
  }));
});

Я использую fakeAsync и tick(), так как мне нужны имитирующие разные queryParams из активированногоRoute в тестах, поэтому я использую 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');
        // ...
      }
    });
  }
...