【问题标题】:Angular: Mocking of HttpClient in Unit TestAngular:在单元测试中模拟 HttpClient
【发布时间】:2020-11-19 04:31:49
【问题描述】:

我有一个使用 httpClient 的服务,我想测试它:

@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' });
  }
}

我的单元测试设置如下所示:

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);
    });
  });
});

很遗憾,测试失败并显示以下消息,我无法让它工作:

TodolistService > #getTodoLists > 应该返回一个 Observable
TypeError: httpMock.expectOne 不是函数

我做错了什么?

提前致谢

【问题讨论】:

  • httpMock = injector.get(HttpClientTestingModule) - 你想要的是控制器,而不是整个模块。

标签: angular unit-testing karma-jasmine angular-unit-test


【解决方案1】:

尝试在beforeEach 中将HttpClientTestingModule 更改为HttpTestingController

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

    injector = getTestBed();
    service = injector.get(TodolistService);
    httpMock = injector.get(HttpTestingController); // <-- here
  });

【讨论】:

  • 从 v9.0.0 开始,getTestBed().get() 已弃用,请改用 TestBed.inject()。请参阅this answer 了解更多信息
猜你喜欢
  • 2019-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 2023-04-07
  • 2021-04-26
  • 1970-01-01
  • 2015-08-24
相关资源
最近更新 更多