我想触发此catch块并确认def gWord(s):
tessr = "".join([ch for ch in s if character(ch) or ch =="'"])
print (tessr)
gWord(" !,Nord's** ")
运行:
handleError()
utilsSvc类:
@Injectable()
export class JwtService {
private actionUrl: string;
private headers: Headers;
constructor(private http: Http, private configurationService: ConfigurationService, private _utilsSvc: UtilitiesService) {}
getToken() {
if (this.configurationService.config) {
return this.http.post(this.configurationService.config.jwtUrl, { "brand": "IAG" })
.map(this._utilsSvc.parseJson)
.catch(this.handleError);
}
}
handleError(error: any) {
let errorStatus = error.status;
return Observable.throw(errorStatus);
}
}
我试图传递它无效的json导致错误被捕获:
@Injectable()
export class UtilitiesService {
constructor(private http: Http) { }
fetchFile(url) {
return this.http.get(url)
.toPromise();
}
parseJson(response: Response) {
return response.json();
}
}
我收到此错误:
TypeError:无法读取属性'符号(Symbol.iterator)'未定义的
如何使catch块捕获错误?
这是我的整个测试文件:
it("Should handle error", () => {
let resOp = new ResponseOptions({
body: "invalid json"
});
mockHttpResponse = new Response(resOp);
mockBackend.connections.subscribe(connection => {
connection.mockRespond(mockHttpResponse);
});
spyOn(jwtService, 'handleError');
jwtService.getToken().subscribe((res) => {
expect(jwtService.handleError).toHaveBeenCalled();
});
});
答案 0 :(得分:0)
问题在这里
spyOn(jwtService, 'handleError');
spyOn将覆盖此方法,因此当catch期望您返回一个observable时,它不会返回任何内容。
要解决此问题,您需要从该方法返回
it("Should handle error", () => {
let resOp = new ResponseOptions({
body: "sdvhfujvn"
});
mockHttpResponse = new Response(resOp);
mockBackend.connections.subscribe(connection => {
connection.mockRespond(mockHttpResponse);
});
spyOn(jwtService, 'handleError').and.callFake(function () {
return Observable.from("fake error");
});
jwtService.getToken()
.subscribe((res) => {
expect(jwtService.handleError).toHaveBeenCalled();
});
});
此测试可行,但我不确定此测试是否有意义