[英]Jasmine Testing Subscription To Service Level Observable From OnInit Angular
[英]Angular 2 observable error testing with jasmine
我想測試這個功能:
register(): void {
let user: User = new User();
user.username = this.username.value;
user.email = this.email.value;
user.password = this.password.value;
this._authService.register(user)
.map(rsp => rsp.json())
.subscribe((response) => { //
this._router.parent.navigate(["Login"]); //
}, (error) => {
this.responseError = JSON.parse(error._body).message;
}, () => {
this._authService.login(user)
.map(rsp => rsp.json())
.subscribe((data: any) => { //
this._authService.handleSuccessLogin(data, user);
this._router.parent.navigate(["../Game"]);
});
});
}
我的_authService
使用 http,但我想偽造那個調用。 我試圖通過它調用並嘲笑 http,但即使我的響應是 4xx,它也運行在成功部分。 是否可以以某種方式測試錯誤部分?
為了模擬一個錯誤,你需要使用mockError
的方法MockConnection
。 它接受一個Error
對象作為參數而不是Response
對象。 為了能夠提供狀態代碼等提示,您可以像這樣擴展Error
類:
class ResponseError extends Error {
status: number;
(...)
}
並以這種方式使用它:
it('Should return something', inject([XHRBackend, HttpService, Injector], (mockBackend, httpService, injector) => {
mockBackend.connections.subscribe(
(connection: MockConnection) => {
if (connection.request.url === 'file1.json') {
var err = new ResponseError();
err.status = 404;
connection.mockError(err);
(...)
在這種情況下,錯誤會在您的數據流中拋出並進入例如subcribe
方法中指定的第二個回調中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.