在 Jasmine 中使用 catchError、throwError

Using catchError, throwError in Jasmine

在我的 angular 项目中有一个带有方法的服务

import { throwError as observableThrowError, Observable } from 'rxjs';   
import { catchError } from 'rxjs/operators';

getUser(): Observable<User> {
  return <Observable<User>>this.http
  .get(`${baseUrl}/api/v1/user`)
  .pipe(
    catchError((error: any) => observableThrowError(error) )
  );
}

在单元测试中,我检查了预期的请求 URL:

it('should have made request to getUser from expected url', () => {
  const expectedUser = { username: 'user' };

  apiService.getUser().subscribe(user => {
    expect(user).toEqual(expectedUser);
  });

  const req = httpTestingController.expectOne(`${baseUrl}/api/v1/user`);
  expect(req.request.method).toEqual('GET');
  req.flush(expectedUser);
});

..而且有效。 但我不知道如何检查错误:

有什么想法吗?

试试这个:

it('should return the error', (done) => { // add done to let Jasmine know when we are done
  const mockErrorResponse = { status: 400, statusText: 'Bad request' };
  const data = 'Invalid request';
  
  apiService.getUser().subscribe(user => {
   
  }, err => {
    expect(err).toBeTruthy();
    done(); // call done to let Jasmine know we are done with our assertions
  });
  const req = httpTestingController.expectOne(`${baseUrl}/api/v1/user`);
  expect(req.request.method).toEqual('GET');
  req.flush(data, mockErrorResponse);
});

也看看这个 and this