我在测试应用程序时遇到了一个问题。主要是我的问题是与URL。这是我的testBed:
let service: AdnimistrationSiteService;
let httpClient: HttpClient
let httpClientMock: HttpTestingController;
let helper : Helper;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule
],
providers: [AdnimistrationSiteService]
});
httpClient = getTestBed().inject(HttpClient);
service = getTestBed().inject(AdnimistrationSiteService);
httpClientMock = getTestBed().inject(HttpTestingController)
helper = new Helper();
});
afterEach(() => {
httpClientMock.verify();
});
it('should be created', () => {
expect(service).toBeTruthy();
});
我要测试的调用看起来像这样:
getAllFilesWithIcons(id_name: string): Observable<any[]> {
let parameters = new HttpParams().set("id_name", id_name);
let url = environment.baseUrl + "/api/v1/example/get_example_api";
return this.http.get(url, {params: parameters})
.pipe(
map(products => products["result"]),
catchError(err => {
console.log(err);
return throwError(err)
})
)
}
我真的不明白这里要测试什么。是对服务器进行真实调用还是模拟调用。如果是,我不知道参数是什么。我试了很多次,但每次都出错。
我的测试是这样的:
it("Should return data", () => {
const testData = [
{'element_filename': 'something', 'icon_symbol': 'symbol_test', "inventory_id": "inv " , "sensors": ["abc " , "eff "]}
]
service.getAllFilesWithIcons("id_name").subscribe((id) => {
console.log(id)
console.log(testData)
expect(testData).toBe(id, "should mocked data")
})
const req = httpClientMock.expectOne(environment.baseUrl + "/api/v1/example/get_example_api" + '?id_name=id_name')
// expect(req.cancelled).toBeFalsy()
expect(req.request.method).toBe("GET")
req.flush(testData)
})
但在这种情况下"id"是未定义的。
id
是未定义的,因为您正在映射到product['result']
,而result
在对象上不存在。
要修复它,请尝试:
it("Should return data", () => {
// !! change this line to have result key !!
const testData = { result: [
{'element_filename': 'something', 'icon_symbol': 'symbol_test', "inventory_id": "inv " , "sensors": ["abc " , "eff "]}
] };
service.getAllFilesWithIcons("id_name").subscribe((id) => {
// id should not be undefined anymore
console.log(id)
expect(id).toBeTruthy();
console.log(testData)
})
const req = httpClientMock.expectOne(environment.baseUrl + "/api/v1/example/get_example_api" + '?id_name=id_name')
// expect(req.cancelled).toBeFalsy()
expect(req.request.method).toBe("GET")
req.flush(testData)
})