在Angular 7中测试http 404错误响应

时间:2019-03-19 10:16:13

标签: angular jasmine rxjs

我有一个api端点,当没有结果时,该端点会返回404错误以进行搜索。在这种情况下,我已经在Angular服务中使用catchError来返回一个空数组。这在运行应用程序时有效,但是我正在尝试为其编写测试用例,并且它从未命中catchError块。我想念什么??

服务代码:

  public searchStuff(query: SearchQuery): Observable<Array<Stuff>> {
    const url: string = `${this.appConfig.baseUrl}/stuffs?title=${query.searchTerm}`;
    return this.httpClient.get<Array<Stuff>>(url).pipe(
      tap(() => console.log('made request')),
      map(data => data.map(stuff => new Stuff(stuff)),
      catchError((error) => {
        if (error.status === 404) {
          console.log('Not Found');
          return of(new Array<Stuff>());
        }

        throw error;
      })
    ));
  }

测试:

  it('should handle a 404 when no search results are found', inject([HttpTestingController], (mockController: HttpTestingController) => {
    const service: SearchService = TestBed.get(SearchService);

    const query: SearchQuery = new SearchQuery();
    query.searchFor = 'stuffs';
    query.searchTerm = 'something';

    service.searchWorks(query).subscribe(results => {
      expect(results).toBeDefined();
    });

    const req = mockController.expectOne(request => {
      return request.url === 'http://localhost/stuffs?title=something' && request.method === 'GET';
    });

    const errorEvent: ErrorEvent = new ErrorEvent('Not Found');
    req.error(errorEvent, { status: 404, statusText: 'Not Found'});
    // req.flush(null, { status: 404, statusText: 'Not Found ' });
    mockController.verify();
  }));

我有一个正面测试,它调用req.flush([]),而在上面的404测试中却没有console.log('made request')

1 个答案:

答案 0 :(得分:0)

在这种情况下,似乎运算符的顺序是关键。 catchError必须在map之前出现,并且所有应用程序和规范都可以正常工作。

  public searchStuff(query: SearchQuery): Observable<Array<Stuff>> {
    const url: string = `${this.appConfig.baseUrl}/stuffs?title=${query.searchTerm}`;
    return this.httpClient.get<Array<Stuff>>(url).pipe(
      tap(() => console.log('made request')),
      catchError((error) => {
        if (error.status === 404) {
          console.log('Not Found');
          return of(new Array<Stuff>());
        }

        throw error;
      }),
      map(data => data.map(stuff => new Stuff(stuff))
    ));
  }