如何测试在flatMap函数内部是否引发了错误?



编写单元测试以确保当某些类型属性与 switch 语句中的大小写不匹配时引发错误。抛出位于执行 flatMap 链并以订阅结束的函数内部。

try/catch 最终不会捕获从调用函数引发的任何内容,尽管当我在订阅结束时添加错误回调时,它引发了正确的错误。

目前,我使用它 try/catch 块来接住投掷,但是我也尝试使用expect(() => {}).toThrow()链但没有成功。

我也尝试使用throwError()而不是throw new Error()

it('should handle unknown list creation', async(() => {
let service = new BlaService(...);
let ids = ['1', '2', '3', '4', '5'];
let listType = 'dfklsjfdkls';
try {
service.handleCreateList(Observable.of({ ids: ids, listType: listType }));
expect(true).toBe('expected exception to be thrown');
} catch (ex) {
expect(ex).toBe(listType + ' is not a recognized list type');
}
// expect( function () {
//   service.handleCreateList(Observable.of({ ids: ids, listType: listType }));
// }
//   ).toThrow(new Error(listType + ' is not a recognized list type'));
}));

public handleCreateList(contextObservable: Observable<any>): void {
// a bunch of lets here
contextObservable.flatMap((context) => {
ids = context.ids;
switch (context.listType) {
case 'constituent':
idsetType = 0;
break;
case ...
break;
default:
// this is the throw we are testing
throw new Error(context.listType + ' is not a recognized list type');
}
return this.resources.getString(context.listType + '_list_name');
}).flatMap((title: string) => {
...
return url;
}).flatMap((url: string) => {
...
return requestResponse;
}).flatMap((response) => {
... // generate a list of observables
return forkJoin(observables);
}).subscribe(() => {
...
// does some navigation stuff here
});
}

通过订阅用作输入的of()的输出并使用其错误回调来修复。此外,实际函数需要返回,而不是订阅,它需要管道和点击。

最新更新