2016-03-26 14 views
6

ben gibi, bir HTTP.post çağrısıyla bir oturum açma yöntemi için Uni-test yazıyorum:angular2 - http.post ünitesi testi hatayı simüle etmek nasıl

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.") 
    ); 

sorun ben değilim ki Hata dalını taklit edebilir; her zaman onLoginComplete Yöntemi denir;

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); 

})); 

tekrar teşekkürler herkese:

burada testtir. HttpServiceHttp nesneyi kullanan hizmettir

describe('HttpService Tests',() => { 
    beforeEachProviders(() => { 
    return [ 
     HTTP_PROVIDERS, 
     provide(XHRBackend, { useClass: MockBackend }), 
     HttpService 
    ]; 
    }); 

    (...) 
}); 

Bildirim o ve ben test etmek istiyorum:

cevap

18

Önce MockBackend biri tarafından XHRBackend sınıf geçersiz kılmak gerekir.

Daha sonra mockBackend'i enjekte etmeniz ve connections özelliğinde abone olmanız gerekir. Bir istek gönderildiğinde, karşılık gelen geri arama denir ve vücut gibi yanıt elemanlarını belirtebilirsiniz. Servis bu cevabı aramanın cevabı olarak alacaktır. Bu sayede servis yönteminizi test edebilirsiniz. Ben HttpService ait getItems yöntemi test etmek nasıl tarif Aşağıda

:

@Injectable() 
export class HttpService { 
    constructor(private http:Http) { 
    } 

    getItems(): Observable<any[]> { 
    return this.http.get('/items').map(res => res.json()); 
    } 
} 

bir hata basitçe mockError kullanmak simüle etmek için: Burada

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 ait getItems yönteminin kodudur yöntem, mockResponse yerine bir yöntem:

mockBackend.connections.subscribe(
    (connection: MockConnection) => { 
     connection.mockError(new Error('some error')); 
    }); 
+11

Küçük bir soru gibi kullanabileceğiniz küçük sınıf

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})); } } 

yarattı dize dışında mockError ile http durum kodu (404, 422, 500, vb)? Benim durumumda, bazı sunucu yanıtları bundan başka bir şey döndürmeyecek. Bir sebepten dolayı, herhangi bir yerde olduğunu gösteren bir örnek bulamadım. –

+1

@LucioMollinedo mevcut RC'de desteklenmediği için. Bunu yapmak için hata düzeltmesi için https://github.com/angular/angular/pull/8961 adresine bakın. Bu arada, kötü birim testleri başka bir vuruş yapmak zorunda kalacak. – Fiddles

+0

Bu çözümün mevcut açısal sürümüne (2.4) uygulanıp uygulanamayacağını merak ediyorum. Buraya uyarlamaya çalıştım: http://stackoverflow.com/questions/42192911/ hayır boşuna ... Birisi size tavsiyede bulunabilir mi? – balteo

2

Böyle bir hata simüle edebilirsiniz: Nasıl bir hata eklersiniz:

connection.mockError(new Response(new ResponseOptions({ 
    body: '', 
    status: 404, 
}))); 

Bu

connection.mockError(new MockError(404)); 
İlgili konular