首页 > 解决方案 > 如何以角度模拟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: ""
  };

标签: angularunit-testingjasmine

解决方案


这是实现此目的的一种方法:

首先,创建一个间谍:

getDataSpy = spyOn(mockService, "getData").and.returnValue(of(mockRecords));

并期望像这样:

it('should succeed', () => {
  // ...setup

  // ...action

  expect(getDataSpy).toHaveBeenCalledWith(filter);
});

不要忘记导入of

import { of } from 'rxjs';

推荐阅读