如何测试flatMap函数内部是否发生错误?

问题描述 投票:0回答:1

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

try / catch最终不会捕获从被调用函数引发的任何东西,尽管我在将on错误回调添加到订阅末尾时看到的错误引发了正确的错误。

[目前,我使用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
        });
    }
angular unit-testing jasmine try-catch throw
1个回答
0
投票

通过订阅用作输入的of()的输出并使用其错误回调来解决。同样,实际的函数需要返回,而不是订阅,它需要通过管道传递并点击。

© www.soinside.com 2019 - 2024. All rights reserved.