angular - 如何以角度模拟api调用
问题描述
我正在对 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';
推荐阅读
- reactjs - 如何将状态从到达路由器传递给链接
- java - 从不同的构造函数访问和添加数据
- python - 通过django social all_auth登录后再次重定向到网页后点击网页时网页正在引用
- html - javascript有特异性吗?
- python - Django 测试不使用 AssertRaises 添加覆盖率
- c# - XAML (WPF) 中使用 GridSplitter 和 GridRows/Columns 定义的大小问题
- javascript - 异步/等待订单
- angular - Angular延迟加载模块导航到子问题
- r - 使用 tidyverse 有什么缺点吗?
- ocr - 为什么 Tesseract 会因此图像出现“空页”而失败?