Angular: Mocking of HttpClient in Unit Test
Asked Answered
G

1

6

I have a service which uses a httpClient that I want to test:

@Injectable({
    providedIn: 'root'
})
export class TodolistService {

  constructor(private http: HttpClient) { }

  getTodoLists(): Observable<HttpResponse<TodoList[]>> {
    return this.http.get<TodoList[]>("https://localhost:44305/todolist", { observe: 'response' });
  }
}

My Unit Test setup looks like this:

import { TestBed, getTestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

import { TodolistService } from './todolist.service';

describe('TodolistService', () => {
  let injector: TestBed;
  let service: TodolistService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule ],
      providers: [ TodolistService ]
    });

    injector = getTestBed();
    service = injector.get(TodolistService);
    httpMock = injector.get(HttpClientTestingModule);
  });

  afterEach(() => {
    httpMock.verify();
  });

  describe('#getTodoLists', () => {
    it('should return an Observable<TodoList[]>', () => {
      const dummyTodoLists = [ 
        { name: "todoList1", listItems: [{id: 1, description: "listitem1-1", done: false}, {id: 2, description: "listitem1-2", done: false}]},
        { name: "todoList2", listItems: [{id: 2, description: "listitem2-1", done: false}, {id: 4, description: "listitem2-2", done: false}]}
      ];
  
      service.getTodoLists().subscribe(todoLists => {
        expect(todoLists.body.length).toBe(2);
        expect(todoLists.body).toEqual(dummyTodoLists);
      });
  
      const req = httpMock.expectOne("https://localhost:44305/todolist");
      expect(req.request.method).toBe("GET");
      req.flush(dummyTodoLists);
    });
  });
});

Unfortunately, the test fails with the following message and I can't get it to work:

TodolistService > #getTodoLists > should return an Observable<TodoList[]>
TypeError: httpMock.expectOne is not a function

What am I doing wrong?

Thanks in advance

Geriatrician answered 29/7, 2020 at 14:35 Comment(1)
httpMock = injector.get(HttpClientTestingModule) - you want the controller, not the whole module.Committeewoman
F
5

Try changing HttpClientTestingModule to HttpTestingController in beforeEach

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule ],
      providers: [ TodolistService ]
    });

    injector = getTestBed();
    service = injector.get(TodolistService);
    httpMock = injector.get(HttpTestingController); // <-- here
  });
Fleisher answered 30/7, 2020 at 4:50 Comment(1)
As of v9.0.0, getTestBed().get() is deprecated, use TestBed.inject() instead. See this answer for more infoCircumvolution

© 2022 - 2024 — McMap. All rights reserved.