上周我将我们的应用程序从Angular 5.8升级到6.我将HttpModule和Http的使用改为使用HttpClientModule和HttpClient . 到目前为止,前端看起来像预期的那样好 . 只是现在一些服务测试失败了,我正在尝试修复它们 . 基本上我有两种类型的服务:
- 直接使用HttpClient的服务 .
客户服务:
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { map } from "rxjs/operators";
import { Observable} from "rxjs";
@Injectable()
export class CustomService {
constructor(private readonly http: HttpClient) { }
someMethod(): Observable<boolean> {
return this.http.get("api/some-url").pipe(
map(res => <boolean>res) }))
);
}
}
- 使用ServiceHelper的服务,该服务使用HttpClient .
客户服务:
import { HttpHeaders } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { SomeRequest } from "../Models/SomeRequest";
import { SomeResult } from "../Models/SomeResult";
import { ServiceHelper } from "./../Helpers/servicehelper";
@Injectable()
export class CustomService {
constructor(readonly serviceHelper: ServiceHelper) { }
someMethod(): Observable<SomeResult> {
const request = {} as SomeRequest;
const headers = new HttpHeaders({ "Content-Type": "application/json" });
const options = { headers: headers };
return this.serviceHelper
.post<SomeRequest, SomeResult>("api/some-url", request, options);
}
}
ServiceHelper:
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { map } from "rxjs/operators";
import { Observable } from "rxjs";
import { Result } from "../Models/Result";
@Injectable()
export class ServiceHelper {
constructor(readonly http: HttpClient) { }
post<Req, Res extends Result>(url: string, request: Req, options): Observable<Res> {
return this.http.post(url, request, options).pipe(
map(data => (data as any) as Res)
);
}
}
第一项服务的测试已经重新开始,通过这样做:
import { TestBed } from "@angular/core/testing";
import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing";
import { HttpResponse } from "@angular/common/http";
import { CustomService } from "./custom.service";
describe("service tests", () => {
let service: CustomService;
let httpClient: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [CustomService]
});
service = TestBed.get(CustomService);
httpClient = TestBed.get(HttpTestingController);
});
it("should pass", () => {
service.someMethod().subscribe(result => {
expect(result).toBe(true);
});
httpClient.expectOne("api/some-url").event(
new HttpResponse<boolean>({ body: true }));
});
});
对于第二个服务(使用ServiceHelper),我想在beforeEach语句中执行类似上面的操作 . 我在configureTestingModule中尝试了一些添加提供程序和/或导入的东西,但是大多数情况下我在运行测试后得到了一个StaticInjectorError .
何我可以为第二类服务编写测试?希望有人可以帮助我!
1 回答
通过将{provide:ServiceHelper,useClass:ServiceHelper}添加到providers数组来修复它 . 固定的configureTestingModule看起来像: