0
votes

I am trying to write unit test for the following function

    public loadValues(): Promise<any> {

      return this._http.get(this.url)
         .toPromise()
         .then((values: any) => {
            this.values = values;
         })
     }

This function is called by the APP_INITIALIZER and thats the reason it is returning a promise instead of observable. I did not find any article to test toPromise, any help will be appreciated.

I have the following test written for it

it('should return app values', async () => {
    const mockValues = {test: 123};
    spyOn(httpClient, 'get').and.returnValue(of(mockValues)).and.callThrough();
    await service.loadValues();
    expect(service.values).toEqual(mockValues);

    const req = httpMock.expectOne(TEST_URL);
    expect(req.request.method).toBe('GET');
});
2
Why would you test a library function? I assure you, the rxjs people test their code.Heretic Monkey

2 Answers

0
votes

Use asyncData helper.
https://angular.io/guide/testing-components-scenarios#async-observable-helpers

it('should return app values', async () => {
    const mockValues = {test: 123};
    spyOn(httpClient, 'get').and.returnValue(asyncData(JSON.parse(mockValues)).toPromise()).and.callThrough();
    await service.loadValues();
    expect(service.values).toEqual(mockValues);

    const req = httpMock.expectOne(TEST_URL);
    expect(req.request.method).toBe('GET');
});

export function asyncData<T>(data: T) {
  return defer(() => Promise.resolve(data));
}
0
votes

I too came also similar task of creating unit tests for the toPromise function. I looked across several articles nowhere I found this thing mentioned. Solution: toPromise waits for the observable to complete. so we have to complete the observable in the tests. I hope this solution works for you.

it('should return app values', fakeAsync () => {
    const mockValues = {test: 123};
    const mockSubject = new Subject<any>(); // create subject of your object type
    spyOn(httpClient, 'get').and.returnValue(mockSubject.asObservable());
    await service.loadValues();
    mockSubject.next(mockValues);
    mockSubject.complete();
    tick();
    expect(service.values).toEqual(mockValues);

    const req = httpMock.expectOne(TEST_URL);
    expect(req.request.method).toBe('GET');
});