[英]angular2 - how to simulate error on http.post unit test
我正在使用HTTP.post調用為登錄方法編寫Uni-test,如:
this.http.post( endpoint, creds, { headers: headers})
.map(res => res.json())
.subscribe(
data => this.onLoginComplete(data.access_token, credentials),
err => this.onHttpLoginFailed(err),
() => this.trace.debug(this.componentName, "Login completed.")
);
問題是我無法模擬錯誤分支; 每次都被稱為onLoginComplete方法;
這是我的測試:
it("check that Atfer Login, console show an error ", inject(
[TraceService, Http, MockBackend, WsiEndpointService],
(traceService: TraceService, http: Http,
backend: MockBackend, wsiEndpoint: WsiEndpointService) => {
let tokenTest: number = 404 ;
let response: ResponseOptions = null {} // i think i have to modify this
let connection: any;
backend.connections.subscribe((c: any) => connection = c);
let authService: AuthService = new AuthService(http, Service1, Service2);
authenticationservice.login({ "username": "a", "password": "1" });
connection.mockRespond(new Response(response));
expect(ERROR);
}));
再次感謝大家。
首先,您需要通過MockBackend
覆蓋XHRBackend
類:
describe('HttpService Tests', () => {
beforeEachProviders(() => {
return [
HTTP_PROVIDERS,
provide(XHRBackend, { useClass: MockBackend }),
HttpService
];
});
(...)
});
請注意, HttpService
是使用Http
對象的服務,我想測試。
然后你需要注入mockBackend並訂閱其connections
屬性。 發送請求時,將調用相應的回調,您可以指定響應元素,如正文。 該服務將接收此響應作為呼叫的響應。 因此,您將能夠基於此測試您的服務方法。
下面我將介紹如何測試HttpService
的getItems
方法:
it('Should return a list of items', inject([XHRBackend, HttpService, Injector], (mockBackend, httpService, injector) => {
mockBackend.connections.subscribe(
(connection: MockConnection) => {
connection.mockRespond(new Response(
new ResponseOptions({
body: [ { id: '1', label: 'item1' }]
})));
});
httpService.getItems().subscribe(
items => {
expect(items).toEqual([ { id: '1', label: 'item1' }]);
});
});
});
這是HttpService
的getItems
方法的代碼:
@Injectable()
export class HttpService {
constructor(private http:Http) {
}
getItems(): Observable<any[]> {
return this.http.get('/items').map(res => res.json());
}
}
為了模擬一個錯誤簡單地使用mockError
方法,而不是mockResponse
之一:
mockBackend.connections.subscribe(
(connection: MockConnection) => {
connection.mockError(new Error('some error'));
});
你可以模擬這樣的錯誤:
connection.mockError(new Response(new ResponseOptions({
body: '',
status: 404,
})));
我創建了一個小班
import {ResponseOptions, Response} from '@angular/http';
export class MockError extends Response implements Error {
name: any;
message: any;
constructor(status: number, body: string = '') {
super(new ResponseOptions({status, body}));
}
}
可以這樣使用
connection.mockError(new MockError(404));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.