How to mock Angular 4.3 httpClient an error response in testing

后端 未结 1 814
暖寄归人
暖寄归人 2020-12-13 18:31

I have a below interceptor auth-interceptor.service.ts

import {Injectable, Injector} from \'@angular/core\';
import {HttpErrorResponse, HttpEven         


        
相关标签:
1条回答
  • 2020-12-13 18:43

    The expectOne method in HttpTestingController class returns a TestRequest object. This TestRequest class has a flush method which can be used to deliver

    both successful and unsuccessful responses.

    We can resolve the request by returning a body along with some additional response headers (if any). Relevant info can be found here.

    Now, coming back to the point how you can do this. You can customize the below code snippet as per your use case.

    http = TestBed.get(HttpTestingController);
    let response: any;
    let errResponse: any;
    const mockErrorResponse = { status: 400, statusText: 'Bad Request' };
    const data = 'Invalid request parameters';
    apiService.get(somePath).subscribe(res => response = res, err => errResponse = err);
    http.expectOne('url/being/monitored').flush(data, mockErrorResponse);
    expect(errResponse).toBe(data);
    

    NOTE: At the time of writing this comment, statusText is required in mockErrorResponse. Related info can be found here.

    P.S.: The error method of TestRequest class can be used to simulate network error in our test case, as it expects an instance of Error. The following code snippet shows that.

    http.expectOne(someUrl).error(new ErrorEvent('network error'));
    
    0 讨论(0)
提交回复
热议问题