【发布时间】:2018-12-21 16:32:54
【问题描述】:
我想简单测试一下我的 todo.service-方法:
create(listId: number, name: string): Observable<TodoItem[]> {
const URL = `${this.apiUrlService.getApiUrl('list')}${listId}/Item`;
return this.http.post(URL, { value: name }).pipe(concatMap(() => this.getAllTodoItemsByListId(listId)));
}
如您所见,它是与 concatMap() 相结合的链式 http 调用;
我最终尝试了几件事,这是我目前的状态:
it('should create an todoItem', fakeAsync(() => {
const mockTodoItem = new TodoItem(1, 1, 'Test1');
let postResponse: TodoItem[];
todoItemService.create(1, 'NameOfList').subscribe((todoItems: TodoItem[]) => {
postResponse = todoItems;
});
tick();
httpMock
.expectOne({
url: `${apiUrlService.getApiUrl('list')}1/Item`,
method: 'POST',
})
.flush(mockTodoItem);
tick();
expect(postResponse).toEqual([mockTodoItem]);
httpMock.verify();
}));
我的 beforeEach():
beforeEach(() => {
TestBed.configureTestingModule({
providers: [TodoItemService, { provide: ApiUrlService, useClass: ApiUrlService }],
imports: [HttpClientTestingModule],
});
todoItemService = TestBed.get(TodoItemService);
httpMock = TestBed.get(HttpTestingController);
apiUrlService = TestBed.get(ApiUrlService);
});
我没有在订阅中得到它。 如果 create 调用看起来像:
create(listId: number, name: string): Observable<TodoItem[]> {
const URL = `${this.apiUrlService.getApiUrl('list')}${listId}/Item`;
return this.http.post(URL, { value: name }));
}
只需执行订阅触发的 POST 请求。 (但显然不是我想要的) 所以我知道我必须以某种方式模拟第二个 GET 调用?!
HttpClientTestingModule 上的 .match() 运算符并没有真正帮助我。
【问题讨论】:
标签: unit-testing rxjs angular7