首页 > 解决方案 > 如何测试 Promise then 方法

问题描述

如何测试 Promise 的 then() 方法中的代码。我没有看到代码的 then(..) 方法中的代码覆盖率。我的单元测试通过并且没有抛出错误,但是当我查看行覆盖率时, toPromise.then(//this code) 里面的代码没有被覆盖。我如何测试该代码。

//service file
getDataFromAPI(num: string): Promise<Model> {
  return this._http
   .get<Model>('url')
   .toPromise()
   .then(resolve => {
       const { item1, item2, item3 } = resolve;
       return { item1, item2, item3 };
  });
}


//unit test
describe('getDataFromAPI', () => {
it('should get data', () => {

  const service: Service = TestBed.get(Service);
  const httpClientGetSpy = jest.spyOn(httpClient, 'get');

  service.getDataFromAPI(num).then(response => {
    expect(response.item1).toEqual('one');
    expect(response.item2).toEqual('two');
    expect(response.item3).toEqual('three');
  });

  expect(httpClientGetSpy).toHaveBeenCalled();
});
});

标签: angulartestingpromise

解决方案


那是因为异步任务。您的测试在承诺之前结束,因此then永远不会调用回调。

只需更改您的测试即可处理async

方法一

fakeAsyncAngular 提供的使用: https ://angular.io/api/core/testing/fakeAsync

it('should get data', fakeAsync(() => {

  const service: Service = TestBed.get(Service);
  const httpClientGetSpy = jest.spyOn(httpClient, 'get');

  service.getDataFromAPI(num).then(response => {
    expect(response.item1).toEqual('one');
    expect(response.item2).toEqual('two');
    expect(response.item3).toEqual('three');
  });

  expect(httpClientGetSpy).toHaveBeenCalled();
}));

方法二

async/await从 ES2016 开始 使用: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

it('should get data', async() => {

  const service: Service = TestBed.get(Service);
  const httpClientGetSpy = jest.spyOn(httpClient, 'get');

  let response = await service.getDataFromAPI(num);
  expect(response.item1).toEqual('one');
  expect(response.item2).toEqual('two');
  expect(response.item3).toEqual('three');

  expect(httpClientGetSpy).toHaveBeenCalled();
});

方法三

当测试应该以done函数结束时处理:

it('should get data', (done) => {

  const service: Service = TestBed.get(Service);
  const httpClientGetSpy = jest.spyOn(httpClient, 'get');

  service.getDataFromAPI(num).then(response => {
    expect(response.item1).toEqual('one');
    expect(response.item2).toEqual('two');
    expect(response.item3).toEqual('three');
    done();
  });

  expect(httpClientGetSpy).toHaveBeenCalled();
});

推荐阅读