简体   繁体   中英

How to test Promise then method

How do I test the code inside the then() method of a Promise. I do not see code coverage for the code inside the then(..) method of my code. My unit test passes and throws no errors, but when I look at line coverage, the code inside toPromise.then(//this code) is not covered. How do I test that 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();
});
});

That's because of asynchronous task. Your test end before promise so then callback is never called.

Just change your test to handle async

Method 1

Use fakeAsync provided by Angular : 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();
}));

Method 2

Use async/await from 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();
});

Method 3

Handle when test should be ended with done function :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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