Angular 5 Unit Testing无法读取undefined的属性'http'

问题描述 投票:0回答:1

我试图在利用HttpTestingController的Angular测试中编写一个辅助函数。原因是因为我最终会在我的Angular服务RequestService中有一系列端点,我想在这个测试文件中测试。我不想反复将RequestServiceHttpTestingController实例注入每个测试服务的测试函数中。这是多余的。相反,我更喜欢有一个测试函数,它接受注入的RequestServiceHttpTestingController实例,并重复将它们传递给我创建的辅助函数requestHelper。这样,当我想测试其他端点时,我需要做的就是调用辅助函数并提供所需的参数。

我遇到的问题是,当辅助函数运行时,服务的实例由于某种原因似乎不存在,即使测试能够访问服务的功能。当它到达我的服务方法调用http.get函数中的callEndpoint时,它给出了以下错误:

Failed: Cannot read property 'http' of undefined

这对我来说没有意义,因为this关键字指的是Angular服务的实例,并且测试用例能够达到服务的功能,那么this怎么可能未定义?

这是我的测试规范:

import { TestBed, async, inject } from '@angular/core/testing';
import { HttpClientModule, HttpRequest, HttpParams } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import {  RequestService } from './request.service';

describe(`RequestService`, () => {

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

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

      it(`TESTING INJECTION`, async(inject([RequestService, HttpTestingController],
        (service: RequestService, backend: HttpTestingController) => {

         requestHelper(service.callEndpoint,'https://endpointurl.com',backend);
      })));

      function requestHelper(serviceCall: Function, url: string,  backendInstance: any) {
        serviceCall(...serviceParams).subscribe();
        backendInstance.expectOne((req: HttpRequest<any>) => {
          return req.url === url
              && req.method === 'GET';
        }, 'GET');
      }
});

以及规范正在测试的相应服务

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';

    @Injectable()
    export class RequestService {

      private requestOptions = {
        headers: new HttpHeaders({'Locale': 'en_US'})
      };

      constructor(private http: HttpClient) { }

      callEndpoint(state: string, countryCode: string): Observable<Object> {
        return this.http.get(`https://endpointurl.com`,this.requestOptions);
      }
}

谢谢您的帮助!

javascript angular jasmine karma-runner
1个回答
1
投票

您可以绑定it块中的上下文:

it(`TESTING INJECTION`, async(inject([RequestService, HttpTestingController],
    (service: RequestService, backend: HttpTestingController) => {

    requestHelper(service.callEndpoint.bind(service),'https://endpointurl.com',backend);
})));
© www.soinside.com 2019 - 2024. All rights reserved.