如何使用Angular中的Jasmine对API服务正确地进行单元测试抛出错误?

时间:2018-11-01 15:43:43

标签: angular unit-testing jasmine

我对Angular和Jasmine框架很陌生。我已经编写了一些包装HttpClient的api服务来进行get / post调用,现在我想对get方法进行单元测试,以确保它正确地捕获并抛出正确的错误。

我的api.service.ts如下:

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class ApiService {

  constructor(private http: HttpClient) { }

  // simple wrapper to throw error
  handleErrors(error: any) {
    return throwError(error);
  }

  /**
   * Method: get(url, { params })
   */
  get(url: string, params: HttpParams = new HttpParams()): Observable<any> {
    return this.http.get(url, { params })
      .pipe(catchError(this.handleErrors));
  }
}

我的api.service.spec.ts如下所示:

import {TestBed, inject, async} from '@angular/core/testing';
import {HttpClientTestingModule, HttpTestingController} from "@angular/common/http/testing";
import {ApiService} from './api.service';
import {HttpClient, HttpErrorResponse, HttpParams} from "@angular/common/http";
import {of} from "rxjs";

describe('ApiService', () => {
  beforeEach(() => TestBed.configureTestingModule({
    imports: [HttpClientTestingModule],
    providers: [ApiService]
  }));

  afterEach(inject([HttpTestingController], (httpMock: HttpTestingController) => {
    httpMock.verify();
  }));

  it('should be created', () => {
    const service: ApiService = TestBed.get(ApiService);
    expect(service).toBeTruthy();
  });

  it('should throw error properly',
    async(
      inject([HttpClient, ApiService], (http: HttpClient, apiService: ApiService) => {
          const err = {status: 404, statusText: 'Not Found'};
          spyOn(http, 'get').and.throwError(JSON.stringify(err))
          apiService.get('testUrl');
          expect(apiService.get).toThrow(JSON.stringify(err));
        }
      )
    )
  );
});

因此,当我运行测试时,我得到的只是一条消息:

Failed: {"status":404,"statusText":"Not Found"}

似乎抛出正确的错误,但测试失败。我在这里对如何编写测试以使其正确知道感到困惑,该错误会抛出handleErrors会捕获并处理的错误,以便使我知道.pipe(catchError(this.handleErrors))确实有效?

谢谢。

1 个答案:

答案 0 :(得分:0)

尝试一下:

expect(error.status).toEqual(404, 'status');
expect(error.error).toEqual(statusText, 'Not Found');