对于无数据场景,我们的 REST 服务返回 204。但我无法弄清楚如何测试这种情况。
it('can handle no data', (done) => {
const testData = service.getDummyData();
service.dataChanged$.subscribe(
(data: Data[]) => {
expect(data).toBeUndefined();
done();
}
);
service.getData();
const request: TestRequest = backend.expectOne(MyService.URL);
request.flush(undefined, { status: 204, statusText: 'No Data' });
});
我试过通过:
- 未定义和错误
Error: Automatic conversion to JSON is not supported for response type.
- 空值
- 响应数据是字符串“null”
那么,我应该将什么传递给 flush 函数以发送空响应?我在服务中测试响应(简化):
this.http.get<Data[]>(MyService.URL)
.first().subscribe(
(data: Data[]) => {
if (data) {
this.dataChanged$.next(data);
} else {
Logger.error(MyService.name, 'getData', 'No data.');
this.dataChanged$.next(undefined);
}
},
(error: Error) => {
Logger.error(MyService.name, 'getData', error.message);
this.dataChanged$.next(undefined);
}
);