任何人都可以建议如何在spec.ts文件中测试下面的catch函数吗?
getTemplate(){
this._http.get('http//localhost:8080/new').map((response : Response) => response.json())).catch(this.serverError);
}
private serverError(err: any) {
console.log('sever error:', err); // debug
if(err instanceof Response) {
//return Observable.throw(err.json().error || 'backend server error');
// if you're using lite-server, use the following line
// instead of the line above:
return Observable.throw(err.text() || 'backend server error');
}
return Observable.throw(err || 'backend server error');
}
答案 0 :(得分:0)
为了测试你需要从服务器接收HttpErrorResponse。要测试这个,您可以编写一个小拦截器,并在监视响应时抛出错误,然后触发您的捕获。
查看这篇文章,它引用了如何编写拦截器以及如何在被请求时生成httperror响应,
在下面的代码中,您还需要确保所有设置和导入都正确完成,下面的代码片段将触发httperror响应,确切地说它将是Http 404.
更新1
以下是示例测试用例文件的样子,假设您的服务名称为 YourService
import {Injectable, ReflectiveInjector} from '@angular/core';
import {async, fakeAsync, tick} from '@angular/core/testing';
import {BaseRequestOptions, ConnectionBackend, Http, RequestOptions} from '@angular/http';
import {Response, ResponseOptions} from '@angular/http';
import {MockBackend, MockConnection} from '@angular/http/testing';
import { YourService } from './serviceIndependent.service';
describe('MockBackend NameService Example', () => {
beforeEach(() => {
this.injector = ReflectiveInjector.resolveAndCreate([
{provide: ConnectionBackend, useClass: MockBackend},
{provide: RequestOptions, useClass: BaseRequestOptions},
Http,
YourService,
]);
this.yourService = this.injector.get(YourService);
this.backend = this.injector.get(ConnectionBackend) as MockBackend;
this.backend.connections.subscribe((connection: any) => this.lastConnection = connection);
});
it('getNames() while server is not Reachable', fakeAsync(() => {
let result: String[];
let catchedError: any;
this.yourService.getNames()
.then((names: String[]) => result = names)
.catch((error: any) => catchedError = error);
this.lastConnection.mockRespond(new Response(new ResponseOptions({
status: 404,
statusText: 'URL not Found',
})));
tick();
expect(result).toBeUndefined();
expect(catchedError).toBeDefined();
}));
});