knbibin
knbibin

Reputation: 1211

How to unit test a function that returns a promise in angular

I have a function inside a component that will call a service method with 3 arguments and that will return a promise. I want to unit test the function using karma jasmine in angular. Did I make any mistakes here?

component code

getHeaderData() {
 return this.service.getList({
    id: this.id,
    name: this.name,
    pageName: constants.PAGE_NAME
  });
}

service code

getList(param): Promise<any> {
 const params = new HttpParams()
    .set('cId',param.id)
    .set('cName',param.name)
    .set('cPageName',param.pageName);
  return new Promise((resolve, reject) => {
   try {
       this.httpService.get('getHeader', {params}).subscribe(data => {
         resolve(data);
        });
   }catch (err){
     reject(err);      
    }
 });
}

spec file code

it('test getHeaderData()', async () => {
  const serviceSpy: Service = TestBed.get(Service);
  SpyOn(serviceSpy, 'getList').and.ReturnValue(Promise.resolve(constants.response));
  expect(serviceSpy.getList).toHaveBeenCalled();
  expect(component.getHeaderData()).toBe(constants.response);
});

the actual return value form the service is an array of objects the same I have created in the constant file as response and with the above code I'm getting below error. I'm not sure this is the right way to do it.

Argument of type is missing the following properties form the ' { then: ExpectedRecursive<{< TResult1 etc......

Upvotes: 3

Views: 18388

Answers (1)

Yevhen Laichenkov
Yevhen Laichenkov

Reputation: 8672

Everything looks good, you've just missed the await keyword, because you're returning a Promise of constants.response (Promise<constants.response>). Hence, you have to await it before verifying.

it('test getHeaderData()', async () => {
  const serviceSpy: Service = TestBed.get(Service);
  SpyOn(serviceSpy, 'getList').and.ReturnValue(Promise.resolve(constants.response));
  expect(serviceSpy.getList).toHaveBeenCalled();

  // Added missed `await` keyword
  expect(await component.getHeaderData()).toBe(constants.response);
});

Upvotes: 10

Related Questions