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



我对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))实际上有效了?

谢谢。

试试这个:

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

最新更新