我在api调用上运行单元测试,我想模拟这个并确保从这个api接收数据的变量被正确设置,这个api必须根据过滤器获取数据。请让我知道如何从api模拟并且如果可能如何确保仅获取满足条件的数据?
this.http.post<someVar[]>('/api/records', this.filter)
.subscribe(res => {
if (res['status'] == "FAILURE") {
console.log(res['err']);
this.spinner.hide();
} else {
this.data = res['data'];
}
从spec.ts模拟
component.filter.from="2019-03-10T22:00:00.000Z";
component.filter.to="2019-04-11T21:59:59.000Z";
mockService.getData=of(mockRecords);//didn't work,so used another one
mockService.getData.and.returnValue(of(mockRecords));
//either of them worked
Also I will mention the filters
filter = {
from : "",
to : "",
id: "",
name: "",
server: ""
};
这是实现此目的的一种方法:
首先,创建一个间谍:
getDataSpy = spyOn(mockService, "getData").and.returnValue(of(mockRecords));
期待这样:
it('should succeed', () => {
// ...setup
// ...action
expect(getDataSpy).toHaveBeenCalledWith(filter);
});
并且不要忘记导入of
:
import { of } from 'rxjs';
```
let getDataSpy=spyOn(mockService,"getData").and.returnValue(of(mockRecords));
component.filter.from="2019-03-10T22:00:00.000Z";//10th march
component.filter.to="2019-04-11T21:59:59.000Z";//11th april
fixture.detectChanges();
expect(getDataSpy).toHaveBeenCalled();//fails
expect(getDataSpy).toHaveBeenCalledWith(filter);//also fails