我需要帮助处理乘客详细信息.service.specs.ts 中的错误的代码覆盖率
以下是我的乘客详细服务代码
import { Injectable } from "@angular/core";
import { Observable, catchError, throwError } from "rxjs";
import {
HttpClient,
HttpErrorResponse,
HttpHeaders,
} from "@angular/common/http";
import { AuthCookiesService } from "@britishairways-ent/cookie";
import { environment } from "src/environments/environment";
import { PassengerApis } from "src/app/interfaces/apis-passenger.interface";
@Injectable({
providedIn: "root",
})
export class PassengerDetailsService {
constructor(
private http: HttpClient,
private authCookiesService: AuthCookiesService
) {}
addApisData(passengerDetails: PassengerApis): Observable<any> {
const url = environment.SAVE_APIS;
return this.http
.post(url, passengerDetails, {
observe: "response",
headers: new HttpHeaders({
"Content-Type": "application/json",
Authorization:
"Bearer " + this.authCookiesService.getPublicAccessToken(),
}),
})
.pipe(catchError(this.handleError));
}
handleError(error: HttpErrorResponse) {
if (
error.error &&
typeof error.error.code !== "undefined" &&
typeof error.error.description !== "undefined"
) {
return throwError(() => error.error.code);
}
}
}
我收到一条警报: 函数未涵盖,语句未涵盖。
您可以测试各种错误响应代码,例如 401、403、404、500。然后,如果您愿意,您可以在 handleError 中对每种情况采取不同的操作。
使用 httpTestingController 设置您的规范并导入 HttpClientTestingModule
import { HttpClientTestingModule, HttpTestingController } from
"@angular/common/http/testing";
describe('PassengerDetailsService', () => {
let service: PassengerDetailsService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
});
service = TestBed.inject(PassengerDetailsService);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
})
it('should handle error 404', () => {
const error = { code: 404, description: 'Not Found' }
service.addApisData({ name: "John Doe", age: 25 }).subscribe({
error: (err) => {
expect(err).toBe(404);
}
});
const req = httpMock.expectOne(environment.SAVE_APIS);
req.flush(error, { status: 404, statusText: 'Not Found' });
});
});