我正在对API调用进行单元测试,我已经验证了API是否可以正确调用。我收到错误,无法读取未定义的属性。我怀疑这是异步代码的问题。
我的API被调用了两次,几乎需要2000毫秒来完成api请求。所以我加了tick(2500)。
还是我期望(component.Financials.length).toBe(1);时仍未定义属性
spec.ts
it('should return one object', fakeAsync(() => {
var dummyObject : any[];
dummyObject = [
{
account: "shjdhjhs",
product: "xyz"
}
];
mockFilter={ account="shjdhjhs"}
//invoking method and intializing filter data
compoenent.filter=mockFilter;
component.Data();
const req = httpMock.expectOne('/api/getrecords');
//fails, as this api is called many times
expect(req.request.method).toBe("POST");
req.flush( dummyObject);
tick(2500);
expect(component.records.length).toBe(1);
//cannot read property of undefined
expect(component.records).toEqual( dummyObject);
}));
ApiCall.ts
Data() {
this.records = [];
this.http.post<Device[]>('/api/getrecords', this.filter)
.subscribe(res => {
if (res['status'] == "FAILURE") {
console.log(res);
} else {
this.records = res['data'];
...
}
}