如何在Angular中模拟API调用

时间:2019-04-11 18:18:15

标签: angular unit-testing jasmine

我正在对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: ""
  };

2 个答案:

答案 0 :(得分:0)

这是完成此任务的一种方法:

首先,创建一个间谍:

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

并期望这样:

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

  // ...action

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

别忘了导入of

import { of } from 'rxjs';

答案 1 :(得分:0)

```
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