繁体   English   中英

如何测试Promise然后方法

[英]How to test Promise then method

如何在Promise的then()方法中测试代码。 我的代码的then(..)方法内部没有看到代码的代码覆盖率。 我的单元测试通过并没有引发任何错误,但是当我查看行覆盖率时,toPromise.then(//此代码)内部的代码未覆盖。 我如何测试该代码。

//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();
});
});

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

只需更改测试以处理async

方法1

使用fakeAsync提供的fakeAsynchttps : 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();
}));

方法2

从ES2016开始使用async/awaithttps : //developer.mozilla.org/zh-CN/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();
});

方法3

处理何时应以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();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM