Angular 5单元测试无法读取未定义的属性http‘
我正尝试在一个利用HttpTestingController
的角度测试中编写一个辅助函数。原因是因为我最终将在我的Angular服务RequestService
中拥有一系列端点,我希望在这个测试文件中对它们进行测试。我不想将我的RequestService
和HttpTestingController
实例重复注入到每个测试服务的测试函数中。这是多余的。相反,我更喜欢使用一个测试函数,该函数接受注入的RequestService
和HttpTestingController
实例,并重复地将它们传递给我创建的助手函数requestHelper
。这样,当我想要测试其他端点时,我所需要做的就是调用helper函数并提供所需的参数。
我遇到的问题是,当helper函数运行时,由于某种原因,服务的实例似乎不存在,即使测试能够访问服务的功能。当它到达我的服务方法对callEndpoint
函数中的http.get
的调用时,它会给我以下错误:
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);
}
}
谢谢你的帮助!
转载请注明出处:http://www.insurance-fj.com/article/20230526/1232516.html