Angular: 单元测试中HttpClient的模拟

5

我有一个使用 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<TodoList[]>
TypeError: httpMock.expectOne 不是一个函数

我做错了什么?

提前感谢。


1
httpMock = injector.get(HttpClientTestingModule) - 你需要的是控制器,而不是整个模块。 - jonrsharpe
1个回答

5
尝试在beforeEach中将HttpClientTestingModule更改为HttpTestingController
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule ],
      providers: [ TodolistService ]
    });

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

4
从v9.0.0开始,getTestBed().get()已被弃用,请改用TestBed.inject()。有关更多信息,请参见此答案 - dansiemens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接