【发布时间】:2019-03-19 10:16:13
【问题描述】:
我有一个 api 端点,当没有结果时返回 404 错误进行搜索。在这种情况下,我在 Angular 服务中使用了 catchError 返回一个空数组。这在运行应用程序时有效,但是我正在尝试为它编写一个测试用例,它永远不会遇到 catchError 块。我错过了什么??
服务代码:
public searchStuff(query: SearchQuery): Observable<Array<Stuff>> {
const url: string = `${this.appConfig.baseUrl}/stuffs?title=${query.searchTerm}`;
return this.httpClient.get<Array<Stuff>>(url).pipe(
tap(() => console.log('made request')),
map(data => data.map(stuff => new Stuff(stuff)),
catchError((error) => {
if (error.status === 404) {
console.log('Not Found');
return of(new Array<Stuff>());
}
throw error;
})
));
}
测试:
it('should handle a 404 when no search results are found', inject([HttpTestingController], (mockController: HttpTestingController) => {
const service: SearchService = TestBed.get(SearchService);
const query: SearchQuery = new SearchQuery();
query.searchFor = 'stuffs';
query.searchTerm = 'something';
service.searchWorks(query).subscribe(results => {
expect(results).toBeDefined();
});
const req = mockController.expectOne(request => {
return request.url === 'http://localhost/stuffs?title=something' && request.method === 'GET';
});
const errorEvent: ErrorEvent = new ErrorEvent('Not Found');
req.error(errorEvent, { status: 404, statusText: 'Not Found'});
// req.flush(null, { status: 404, statusText: 'Not Found ' });
mockController.verify();
}));
我有一个调用req.flush([]) 的阳性测试,这是console.log('made request'),而上面的404 测试没有。
【问题讨论】:
-
你也应该把你的断言放在你订阅的错误部分。您返回错误,但单独检查 next() 回调。
-
@KiraAG 这将是一个标准的断言,但是我希望 404 被抑制并从服务返回一个空数组。
-
你能去掉点击并检查吗?实际上 tap 没有返回任何东西,你应该从 tap 返回以传播给 map 操作符。