gpt4 book ai didi

Angular:在单元测试中模拟 HttpClient

转载 作者:行者123 更新时间:2023-12-04 14:12:29 26 4
gpt4 key购买 nike

我有一个使用 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 > should return an Observable<TodoList[]>
TypeError: httpMock.expectOne is not a function

我做错了什么?

提前致谢

最佳答案

尝试在 beforeEach 中将 HttpClientTestingModule 更改为 HttpTestingController

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

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

关于Angular:在单元测试中模拟 HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63156059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com