简体   繁体   English

使用 callFake() 测试 HttpClient 调用

[英]Testing HttpClient call with callFake()

I am trying to create a spec to test a method in my Angular service that makes a GET request.我正在尝试创建一个规范来测试我的 Angular 服务中发出 GET 请求的方法。 The difficulty I am having is mocking the method to get it to return an error instead of the response.我遇到的困难是模拟方法以使其返回错误而不是响应。 If I cannot get it to return an error (such a 400 or 500 for example) I cannot provide full code coverage...如果我无法让它返回错误(例如 400 或 500),我将无法提供完整的代码覆盖率...

Code being tested:正在测试的代码:

maingrid.service.ts: maingrid.service.ts:

 async loadAccountListPromise(id: string) {
     let queryParams = `?emailAddress=${id}`;
     let promise = new Promise((resolve, reject) => {
          this.http.get(`${this.baseUrl}` + queryParams, { responseType: 'json' })
             .toPromise()
             .then(
             (data) => {
                 this.results = this.formatData(data);
                 resolve(this.results);
             },
             (err) => {
                 this.logService.error('loadAccountListPromise() exception:', err);
                 this.setError(this.message[0], err);
                 reject('loadAccountListPromise() exception');
             }
         );
     });
     return promise;
 }

 setError(errorMessage: string, errorCode?: string): void {
     this._error.next(new NxpError(errorMessage, 'AccountListService', 
     errorCode));
 }

 clearError(): void {
     this._error.next(null);
 }

This is the spec I have attempted to write to mock the method using callFake():这是我尝试编写的使用 callFake() 模拟方法的规范:

maingrid.service.spec.ts maingrid.service.spec.ts

    it('logs and sets a local error for system errors/exceptions', () => {

            let id: string = 'ppandya@pershing.com';
            let myUrl = 'https://localhost:9999/...';
            let queryParams = `?emailAddress=${id}`;

            spyOn(httpClient, 'get').and.callFake( loadAccountListPromise( (response) => {
                // need to return error here...somehow
            }));

            spyOn(logService, 'error');

            spyOn(maingridService, 'setError');

            maingridService.loadAccountListPromise(id);

            let request = httpMock.expectOne(myUrl + queryParams);

            expect(request.request.method).toEqual('GET');

            httpMock.verify();

            expect(logService.error).toHaveBeenCalled();
            expect(maingridService.setError).toHaveBeenCalled();
        });

I am not sure what I need to do to properly mock the loadAcountListPromise() method so that it enters the error block and calls the setError() and logService.error() methods.我不确定我需要做什么才能正确模拟 loadAcountListPromise() 方法,以便它进入错误块并调用setError()logService.error()方法。

Try to use the 'spyOn()' and return a throw like this:尝试使用 'spyOn()' 并返回如下抛出:

spyOn(httpClient, 'get').and.returnValue(Observable.throw({status: 404}));
//Observable.throw(new Error(`Error: ${error}`));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM