Angular - 如何测试调用回调的方法

Angular - How to test method that calls a callback

我将 Angular 11 与打字稿一起使用,但我不知道如何测试该方法引发异常的路径。

  myMethod() {
    this.myService.callBackend(id).subscribe(() => {
       // do something when success
    }, responseKo => {
      if (responseKo instanceof HttpErrorResponse) {
        if (responseKo.status === 400) {
          // do something when we have bad request
        } else {
          throw responseKo;
        }
      } else {
        throw responseKo;
      }
    });
  }

我使用 jasmine 和 karma 作为测试框架。

抛出异常时如何测试路径?

我假设您在测试设置的某个时刻使用间谍方法模拟您的服务。使您的测试通过错误方式只是 return 从您的方法中观察到的错误。使用 throwError 可观察创建 fn

it('it should react to errors', () => {
  serviceMock.callBackend.and.returnValue(throwError(myErrorObject));
  myComponent.myMethod();
});

observables 的实现考虑到了处理异步性的能力。所以你将需要在 fakeAsync 的帮助下使你的测试异步。在 fakeAsync 测试 tick 函数中,您可以异步地“刷新”所有发生的事情。在你的情况下,可以利用它,并期望 tick 抛出。像这样:

 it('should throw', fakeAsync(() => {
    of(true).subscribe(() => {
        throw new Error('something thrown');
    });
    expect(tick).toThrow();
  }));