【问题标题】:Angular 7 - catching HttpErrorResponse in unit testsAngular 7 - 在单元测试中捕获 HttpErrorResponse
【发布时间】:2018-12-04 14:52:49
【问题描述】:

我目前正在学习 Angular 7(没有使用任何以前的版本)并且在为服务编写单元测试时遇到了一些我无法修复的问题。

我有一个从 REST 获取 JSON 并将其解析为类的服务。 参考 Angular Docs,我使用 HttpClientSpy 编写了一个测试来模拟 404 错误。

会发生什么:测试失败并显示错误消息:“expected data.forEach is not a function to contain '404'”

因此,服务将 HttpErrorResponse 作为输入,但尝试将其解析为 map 函数中的常规响应。这失败了,catchError 被调用并且 data.forEach is not a function 被抛出。

预期行为:我希望 map() 没有被执行,它应该直接跳转到 catchError 函数中。

我是如何修复它的(目前):将以下代码行添加到服务的 map 函数中可以使测试工作。

if (data instanceof HttpErrorResponse)
      throw new HttpErrorResponse(data);

测试:

it('should throw an error when 404', () => {

const errorResponse = new HttpErrorResponse({
  error: '404 error',
  status: 404, statusText: 'Not Found'
});

httpClientSpy.get.and.returnValue(of(errorResponse));

service.getComments().subscribe(
  fail,
  error => expect(error.message).toContain('404')
);
});

服务:

getComments(): Observable<CommentList> {
return this.http
.get('https://jsonplaceholder.typicode.com/comments')
.pipe(
  map((data: Array<any>) => {
    let t: Array<Comment> = [];

    data.forEach(comment => {

      if(!('id' in comment) || !('body' in comment) || !('email' in comment) || !('name' in comment))
        throw new Error("Could not cast Object returned from REST into comment");

      t.push(<Comment>{
        id: comment.id,
        body: comment.body,
        author: comment.email,
        title: comment.name,
      });

    });
    return new CommentList(t);
  }),
  catchError((err: HttpErrorResponse) => {
    return throwError(err);
  })
);
}

我有什么问题吗?我认为预期的行为是我应该经历的,至少这就是我解释 Angular 文档的方式。

【问题讨论】:

  • 您不使用HttpClientTestingModule 来测试使用HttpClient 的服务有什么特别的原因吗?文档展示了如何测试错误:angular.io/guide/http#testing-for-errors。此外,您不是在嘲笑 get 引发错误,而是在嘲笑它解析为 data = errorResponse,因此它在 .forEach 上窒息。

标签: angular rest http testing karma-runner


【解决方案1】:

一个迟到的答案,一个稍微不同的方式,但这也有效。

  it('should show modal if failed', inject([Router], (mockRouter: Router) => {
  const errorResponse = new HttpErrorResponse({
     error: { code: `some code`, message: `some message.` },
     status: 400,
     statusText: 'Bad Request',
  });

  spyOn(someService, 'methodFromService').and.returnValue(throwError(errorResponse));
  expect...
  expect...
  expect...
}));

【讨论】:

  • 搜索了几个小时,找到了这个答案,太棒了!谢谢。
【解决方案2】:

迟到的答案,但可能对面临类似问题的人有所帮助。

根本原因

错误消息:“expected data.forEach is not a function to contain '404'”是因为测试用例中的 of 运算符:

httpClientSpy.get.and.returnValue(of(errorResponse));

of 运算符返回一个发出参数的 observable。

这在您想要返回数据时很有用,但在您想要引发 404 错误时则不然。

为了让间谍提出错误,响应应该拒绝而不是解决。

解决方案 1

此解决方案使用defer RxJS 运算符以及您在示例中使用的jasmine.createSpyObj 方法。

import { TestBed } from '@angular/core/testing';
import { HttpErrorResponse } from '@angular/common/http';
import { defer } from 'rxjs';

import { CommentsService } from './comments.service';

// Create async observable error that errors
//  after a JS engine turn
export function asyncError<T>(errorObject: any) {
  return defer(() => Promise.reject(errorObject));
}

describe('CommentsService', () => {
  let httpClientSpy: { get: jasmine.Spy };
  let service: CommentsService;

  beforeEach(() => {
    httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
    service = new CommentsService(httpClientSpy as any);
  });

  it('should throw an error when 404', () => {
    const errorResponse = new HttpErrorResponse({
      error: '404 error',
      status: 404,
      statusText: 'Not Found'
    });

    httpClientSpy.get.and.returnValue(asyncError(errorResponse));

    service.getComments().subscribe(
      data => fail('Should have failed with 404 error'),
      (error: HttpErrorResponse) => {
        expect(error.status).toEqual(404);
        expect(error.error).toContain('404 error');
      });
  });
});

解决方案 2

最好使用角度HttpClientTestingModule 来测试HttpClient 的用法。以下示例显示了使用 HttpClientTestingModule 的相同测试。

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpErrorResponse } from '@angular/common/http';

import { CommentsService } from './comments.service';

describe('CommentsService test using HttpClientTestingModule', () => {
  let httpTestingController: HttpTestingController;
  let service: CommentsService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule ]
    });

    httpTestingController = TestBed.get(HttpTestingController);
    service = TestBed.get(CommentsService);
  });

  it('throws 404 error', () => {
    service.getComments().subscribe(
      data => fail('Should have failed with 404 error'),
      (error: HttpErrorResponse) => {
        expect(error.status).toEqual(404);
        expect(error.error).toContain('404 error');
      }
    );

    const req = httpTestingController.expectOne('https://jsonplaceholder.typicode.com/comments');

    // Respond with mock error
    req.flush('404 error', { status: 404, statusText: 'Not Found' });
  });
});

角度 HTTP Testing 文档解释了这种方法。

注意:这些示例是使用 Angular v8 测试的。

【讨论】:

    猜你喜欢
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多