我想简单地测试我的 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 Call吗?!
HttpClientTestingModule上的 .match()运算符并没有真正帮助我。答案 0 :(得分:0)
您将需要模拟从getAllTodoItemsByListId
返回的内容。也许是这样的:
it('should create an todoItem', fakeAsync(() => {
const mockTodoItem = new TodoItem(1, 1, 'Test1');
spyOn(todoItemService, 'getAllTodoItemsByListId').and.returnValue(of(mockTodoItem));
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();
}));
如果您还没有导入,可能还需要此导入:
import { of } from 'rxjs';