1

In my angular project there is a service with a method

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) )
  );
}

In the unit test I check request to expected 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);
});

..and it works. But I don't know how to check if the error:

enter image description here

Any ideas?

Alex
  • 409
  • 3
  • 18

1 Answers1

2

Try this:

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);
});

Check out this link and this link as well.

AliF50
  • 16,947
  • 1
  • 21
  • 37