Unit Service Testing Using Karma (typescript/angular)

Asked

Viewed 644 times

1

I’m trying to test a service GET method:

get(url: string, params?: any): Observable<Response> {
    let options = {};
    this.securityService.setHeaders(options);

    if (params)
        this.setParams(options, params.params);

    return this.http.get(url, options)
        .pipe(
            // retry(3), // retry a failed request up to 3 times
            map((res: Response) => {
                return res;
            }),
            catchError(this.handleError)
        );
}

The method setHeaders insert the request headers and the access_token, I can test it up to the part of the map but I can’t test the return part. It would have some solution to write a test to go through the entire method?

Obs.: The method of setParams is already being guaranteed by another test.

1 answer

0

I would do something like this:

  it('get should call correct api with correct payload', () => {
    let httpClient = TestBed.get(HttpClient);
    const obj = { response: 'superResponse' };
    const mockHttp = spyOn(httpClient, 'get').and.returnValue(of(obj));

    service.get('fakeUrl').subscribe(response => {
      expect(response).toEqual(obj);
    });

    const options={};

    expect(mockHttp).toHaveBeenCalledWith(
      'fakeUrl',
     options,
    );
  });
  • I tried the solution and it returned me an error, I believe it is something in Spy: Expected Spy get to have been called with [ 'fakeUrl', Object(ː }) ] but it was Never called.

  • Take a look if you are using httpClient or the older version

Browser other questions tagged

You are not signed in. Login or sign up in order to post.