Rinktacular
Rinktacular

Reputation: 1126

Getting error this.httpClient.get(...).map is not a function when running ng test

I am trying to understand how to create an htpClientSpy, as per the Angular documentation on testing services. Currently I have this set up:

import { TestBed } from '@angular/core/testing';
import { AuthService } from '../../../core/auth/auth.service';
import { PermissionsService } from '../services/permissions.api.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';

describe('PermissionsService', () => {

  let permissionsService: PermissionsService;
  let httpClientSpy: { get: jasmine.Spy };
  let authClientSpy: { get: jasmine.Spy };

  beforeEach(() => {
    httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
    authClientSpy = jasmine.createSpyObj('Http', ['get']);
    permissionsService = new PermissionsService(new AuthService( <any> authClientSpy), <any> httpClientSpy);
  });

  it('should refresh global permissions using refreshGlobalPermissions', () => {
    const mockGlobalResponse = { global_actions: ['permission1', 'permission2', 'permission3']};
    httpClientSpy.get.and.returnValue(mockGlobalResponse);
    permissionsService.refreshGlobalPermissions().subscribe(
      permissions => expect(permissions).toEqual(mockGlobalResponse, 'expected global permissions'),
      fail
    );
    expect(httpClientSpy.get.calls.count()).toBe(1, 'one call');
  });
}

However, when I run my ng test from the console (and this is my only test) I get this error:

TypeError: this.httpClient.get(...).map is not a function

From what I am finding, all I should need to do is import map in my *.spec.ts file but that does not seem to work. Is there something I am missing here?

EDIT: Service I am testing:

public refreshGlobalPermissions(): any {
    const globalPermissions = this.globalPermissions;
    if (globalPermissions.length === 0) {
      const url = `${this.baseUrl}?permissions`;
      return this.httpClient.get(url).map((response) => {
        this.globalPermissions = response['global_actions'];
      });
    }
    return Observable.of(true);
  }

Upvotes: 1

Views: 2105

Answers (1)

JB Nizet
JB Nizet

Reputation: 692201

HttpClient.get() returns an Observable. Your production code calls map() on this Observable.

But in your code, your spy of the get() method doesn't return an Observable. It returns mockGlobalResponse, which is a POJO. So that can't possibly work.

I suggest you don't spy the HttpClient this way, and instead use the testing support dedicated to HttpClient, and described in the documentation.

Upvotes: 2

Related Questions