In my Angular 12 project, I am facing an issue with setting up unit tests that should capture errors from HTTP responses. However, when running the tests, instead of receiving the error as an actual error object, it is being passed within the response body.
Here is a snippet from my Spec.ts file:
it('Test post method failure', () => {
const expected: HttpErrorResponse = new HttpErrorResponse({
error: 'Bad Request',
status: 400,
statusText: 'Bad Request'
});
service.post({ urlIdentifier: 'test', endpoint: '123' }).subscribe({
next: res => {
// This block is executed
console.log(res)
},
error: error => {
// This block is not getting executed
expect(error.status).toBeCloseTo(expected.status);
expect(error.statusText).toEqual(expected.error);
}}
);
Below is the method being tested in the HttpService class:
export class HttpService {
constructor(public http: HttpClient) {};
post<T>({ urlIdentifier, endpoint, body }: HttpMethodsArguments): Observable<T> {
const url: string = this.getBaseUrl(urlIdentifier) + endpoint;
return this.http.post<T>(url, body, {
headers: this.getHttpHeaders()
}).pipe(
catchError(err => {
return throwError(err);
})
);
}
The response object LOG shows: HttpErrorResponse(headers:..., status:400, statusText: "Bad Request" ...) The expected outcome is embedded in the response object in the test instead of triggering an error. I suspect there's a small detail that I'm overlooking, but I haven't been able to figure it out yet.