我正在为angular2服务编写单元测试。代码段:
// jasmine specfile
// already injected MockConnection into Http
backend.connections.subscribe ((c: MockConnection) => {
connection = c;
});
// doing get-request
myServiceCallwithHttpRequest ().subscribe (result => {
// this test passes!
expect (result).toEqual ({
"message": "No Such Object"
});
// this test fails, don't know how to get the response code
expect (whereIsResponseStatus).toBe (404);
});
connection.mockRespond (new Response (new ResponseOptions ({
body: {
"message": "No Such Object"
},
status: 404
})));
我的服务:
// service
myServiceCallwithHttpRequest (): Observable<Response> {
return this.http.get ('/my/json-service').map (res => {
// res.status == null
return res.json ()
})
.catch (this.handleError); // from angular2 tutorial
}
第一个期望是好的,程序进入地图调用,而不是捕获。但是如何获取状态代码404? res.status为null。
答案 0 :(得分:36)
要使模拟错误起作用,您需要从@ angular / http导入ResponseType并在模拟响应中包含错误类型,然后扩展Response并实现错误
{{1}}
答案 1 :(得分:2)
在node_modules\@angular\http\testing\mock_backend.d.ts
处查看源代码。
MockConnection.mockRespond
已在您的代码中。
MockConnection.mockError
是您可能需要的。
玩它,看看你得到了什么。
答案 2 :(得分:1)
您需要在.subscribe
上使用observable
来注册success
,error
&amp; completed
回拨
<强>代码强>
myServiceCallwithHttpRequest (): Observable<Response> {
return this.http.get ('/my/json-service').map (res => {
// res.status == null
return res.json ()
})
.subscribe(
data => this.saveJwt(data.id_token), //success
err => { //error function
//error object will have status of request.
console.log(err);
},
() => console.log('Authentication Complete') //completed
);
//.catch (this.handleError); // from angular2 tutorial
}
答案 3 :(得分:0)
适合我:
mockConnection.mockRespond (new Response (new ResponseOptions ({
body: {},
status: 404
})));