我正在尝试使用Angular HttpClientTestingModule测试我的Angular API服务。我读了一些教程,如何使用HttpClientTestingModule。 但是,如果我使用此功能,则会收到未定义的响应。
这是我要测试的服务
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import * as log from "loglevel";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";
import { itemHistoryURL } from "../../../../urls";
import { IHistoryObject } from "../item-history-service/item-history.service";
@Injectable({
providedIn: "root"
})
export class ItemHistoryApiService {
readonly default_headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods":
"Origin, X-Requested-With, Content-Type, Accept",
"Content-Type": "application/json"
};
constructor(public http: HttpClient) {}
public fetchItemHistory(itemId: string, itemType: string): Observable<any> {
log.debug(
"Trying to fetch the complete history for item in API Service",
itemId
);
return this.http
.get(itemHistoryURL + "/itemhistory/" + itemType + "/" + itemId, {
headers: this.default_headers
})
.pipe(
map((response: any) => {
const historyList: IHistoryObject[] = response.data;
return historyList;
})
);
}
这是我的测试班
import { TestBed } from "@angular/core/testing";
import {
HttpClientTestingModule,
HttpTestingController
} from "@angular/common/http/testing";
import { itemHistoryURL } from "../../../../urls";
import { ItemHistoryApiService } from "../item-history-api-service/item-history-api.service";
describe("ItemHistoryService", () => {
let httpTestingController: HttpTestingController;
let service: ItemHistoryApiService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [ItemHistoryApiService]
});
httpTestingController = TestBed.get(HttpTestingController);
service = TestBed.get(ItemHistoryApiService);
});
afterEach(() => {
httpTestingController.verify();
});
it("should be created", () => {
expect(service).toBeTruthy();
});
fit("should be fetch all HistoryData for an item", () => {
const dummyHistoryList = [
{
changedBy: "Jens",
changedAt: "15667867868568",
changes: [
{
changeType: "ValueChange",
property: "eventName",
propertyChangeType: "PROPERTY_VALUE_CHANGED",
entryChanges: [
{
entryChangeType: "",
key: "",
leftValue: "",
rightValue: ""
}
],
left: "ItemCreated",
right: "ItemPayloadChanged"
},
{
changeType: "ValueChange",
property: "costCenter",
propertyChangeType: "PROPERTY_VALUE_CHANGED",
entryChanges: [
{
entryChangeType: "",
key: "",
leftValue: "",
rightValue: ""
}
],
left: "44534",
right: "FCX_GW"
}
]
}
];
service.fetchItemHistory("test", "test").subscribe(data => {
console.log(data);
expect(data).toEqual(dummyHistoryList);
}, fail);
const req = httpTestingController.expectOne(
itemHistoryURL + "/itemhistory/" + "test" + "/" + "test"
);
expect(req.request.method).toBe("GET");
req.flush(dummyHistoryList);
});
});
测试类中的console.log(data)
总是返回undefined而不是我的测试响应对象。