如何捕获测试中可观察的订阅引发的异常

时间:2018-09-20 20:54:12

标签: angular jasmine observable

我不确定如何在Angular 6中处理带有URL参数的异常。现在,当找不到URL ID时,我的服务将抛出Error。在实际的应用程序中,我喜欢将错误冒泡起来并记录下来,但是在我的茉莉花测试中,这会导致测试失败:

HeroDetailComponent should navigate to not found page
[object ErrorEvent] thrown

我已经尝试了各种try {} catch () {}块和catchError管道来处理茉莉花中的错误,但是在测试预期运行之后,似乎没有任何东西可以捕获此错误。

问题的演示:https://angular-observable-catch.stackblitz.io/

请注意,在stackblitz上测试不会失败,但是在使用ng test在我的应用程序中运行时,它将在本地进行。

在(主)控制台中记录错误:

Uncaught Error: Hero 999 not found.
    at HeroService.getHeroById (hero.service.ts:33)
    at SwitchMapSubscriber.eval [as project] (hero-detail.component.ts:46)
    at SwitchMapSubscriber._next (switchMap.ts:103)
    at SwitchMapSubscriber.Subscriber.next (Subscriber.ts:104)
    at ReplaySubject.Subject.next (Subject.ts:62)
    at ReplaySubject.nextInfiniteTimeWindow (ReplaySubject.ts:42)
    at ActivatedRouteStub.setParamMap (activated-route-stub.ts:56)
    at UserContext.eval (hero-detail.component.spec.ts:65)
    at ZoneDelegate.invoke (zone.js:388)
    at ProxyZoneSpec.onInvoke (zone-testing.js:288)

演示的源代码:https://stackblitz.com/edit/angular-observable-catch?file=src%2Fapp%2Fhero%2Fhero-detail.component.spec.ts

如何在茉莉花测试中捕获此错误,从而不会导致未捕获的错误?


更新

我发现这是由AsyncPipe subscription引起的,它引发了Observable / Promise / etc等任何错误。

1 个答案:

答案 0 :(得分:0)

我发现此问题的一种解决方法是用不会引发错误的代码替换TestBed中的AsyncPipe。

test-async-pipe.ts:

import { AsyncPipe } from '@angular/common';
import { Pipe } from '@angular/core';

/**
 * When the AsyncPipe throws errors Jasmine cannot catch them and causes tests to fail.
 * For tests just log the error and move on.
 * Add this class to the TestBed.configureTestingModule declarations.
 */
@Pipe({name: 'async', pure: false}) // tslint:disable-line:use-pipe-transform-interface
export class TestAsyncPipe extends AsyncPipe {
  transform(obj: any): any {
    const ret = super.transform(obj);
    const handleError = (err: any) => { console.error('AsyncPipe Template Exception', err); };
    // @ts-ignore: patch the Observable error handler to not throw an error in tests.
    this._subscription.destination._error = handleError;
    // What if the subscription is a Promise?
    return ret;
  }
}

a-test.spec.ts

import { async, TestBed } from '@angular/core/testing';

import { TestAsyncPipe } from '../testing/test-async-pipe';

import { TestComponent} from './test.component';

describe('TestComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ TestAsyncPipe, TestComponent],
    })
    .compileComponents();
  }));
});