Тестирование наследования httpClient в Angular 6 - PullRequest
0 голосов
/ 16 октября 2018

Я расширил httpClient в проекте ng, чтобы добавить пользовательский параметр в параметры.(Это прекрасно работает в моем приложении)

Мой новый сервис выглядит так:

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

Я пытаюсь выполнить модульное тестирование этой пользовательской реализации, но я получаю следующую ошибку вauseOne

Ошибка: ожидается одно совпадениезапрос по критерию «Совпадение по функции:», найдено 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();
      }));

    });

Чего мне не хватает?

1 Ответ

0 голосов
/ 16 октября 2018

Выяснил ошибку, метод подписки, который я использую в пользовательском запросе, вызывал повторный вызов, так что это исправило проблему:

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