首页 > 解决方案 > 在Angular 6中测试httpClient的继承

问题描述

我在 ng 项目中扩展了 httpClient,以便为选项添加自定义参数。(这在我的应用程序中运行良好)

我的新服务如下所示:

  export class CustomHttpClient extends HttpClient {

    request(first: string | HttpRequest<any>, url?: string, options: CustomHttpOptions = {}): Observable<any> {

        const res = super.request(first as string, url, options);
        res.subscribe(
            () => { // Success
                // Some action on success
            },
            () => { // error
                // Some action on error
            }
        );
        return res;
    }

    post(url: string, body: any | null, options: CustomHttpOptions = {}): Observable<any> {
        return this.request('POST', url, addBody(options, body));
    }

    put(url: string, body: any | null, options: CustomHttpOptions = {}): Observable<any> {
        return this.request('PUT', url, addBody(options, body));
    }

    patch(url: string, body: any | null, options: CustomHttpOptions = {}): Observable<any> {
        return this.request('PATCH', url, addBody(options, body));
     }
    }

      function addBody<T>(options: CustomHttpOptions, body: T | null) {
        const opts = { ...options, body };
        return opts;
      }

      export interface CustomHttpOptions {
        body?: any;
        headers?: HttpHeaders | { [header: string]: string | string[]; };
        observe?: 'body' | HttpObserve | any;
        params?: HttpParams | { [param: string]: string | string[]; };
        reportProgress?: boolean;
        responseType?: 'arraybuffer' | 'blob' | 'json' | 'text' | any;
        withCredentials?: boolean;
        customParameter?: boolean;
     }

我正在尝试对这个自定义实现进行单元测试,但在 expectOne 中出现以下错误

错误:应为条件“按功能匹配:”提供一个匹配请求,但找到了 2 个请求。

这是我正在做的单元测试

    describe('CustomHttpClient', () => {

    const httpOptions: CustomHttpOptions = {
        CustomParameter: true
    };

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [CustomHttpClient]
        });
    });

    afterEach(inject([HttpTestingController], (httpMock: HttpTestingController) => {
        httpMock.verify();
    }));

    it('receive the optional parameter for a GET method', inject([CustomHttpClient, HttpTestingController], (http: CustomHttpClient, httpMock: HttpTestingController) => {

  
        http.get('/data', httpOptions).subscribe(
            response => {
                expect(response).toBeTruthy();
            }
        );

        const req = httpMock.expectOne((request: HttpRequest<any>) => {
            return request.method === 'GET';
        });

        expect(req.request.method).toEqual('GET');
        httpMock.verify();
      }));

    });

我错过了什么?

标签: angularunit-testinginheritancejasmineangular-httpclient

解决方案


找出错误,我在自定义请求中使用的订阅方法导致重复调用,所以这解决了问题:

super.request(first as string, url, options).pipe(share());

推荐阅读