0
votes

In component:

private xxxService: XxxService,

const xxxList = await this.xxxService.getSomething(this.someid).toPromise();

In testing file component.spec.ts:

import {Observable, of} from 'rxjs';
const xxxServiceStub = {
    getSomething: () => Promise.resolve([])
  };
 beforeEach((async(next) => {
    await TestBed.configureTestingModule({
      declarations: [someComponent],
      imports: [
       ....
      ],
      providers: [
        {provide: XxxService, useValue: xxxServiceStub},
      ]
    }).compileComponents();
    next();
  }));

API:

public getSomething(someid): Observable<xxxRef[]> {
    return this.httpClient
      .get<xxxRef[]>(
        ${environment.url}/api/xxx?someid=${someid},
        {
          observe: 'response'
        }
      ).pipe(
        map(response => {
          return response.body;
        })
      );
  }

Interface:

export interface xxxRef {
  name: string;
  id: number;
  description?: string;
}

Test goes, but there is a mistake in console of Karma:

zone-evergreen.js:798 Uncaught Error: Uncaught (in promise): TypeError: this.xxxService.getSomething(...).toPromise is not a function

2

2 Answers

0
votes

It's hard to tell you the exact issue without knowing what xxxServiceStub is but, it is likely due to the fact that you aren't returning a Observable (which has the .toPromise function

Your faked xxxService.getSomething needs to look something like this in order for it to work in the spec:

getSomething(id: number): Observable<any> {
  return of(true);
}

An alternative would be to use a spy:

spyOn(xxxService, 'getSomething').and.callFake(() => of(true));
0
votes

You need to return an Observable from getSomething method but you're returning Promise.resolve which not an Observable, that's why you're getting error.

Change your mock method to this

import { of } from 'rxjs';

...
const xxxServiceStub = {
    getSomething: () => of([]) // this returns observable 
};

toPromise reference

mock toPromise