2016-02-16 16 views
20

Sto scrivendo unit test per un servizio angular2. Frammenti di codice:come simulare l'errore http per il test 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 
}))); 

mio servizio:

// 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 
} 

Il primo si aspettano è OK, il programma va in chiamata carta, non è la cattura. Ma come ottengo il codice di stato 404? res.status è nullo.

risposta

-1

funziona per me:

mockConnection.mockRespond (new Response (new ResponseOptions ({ 
     body: {}, 
     status: 404 
    }))); 
+2

Non ha funzionato per me, questo ha attivato il 'NextObserver' invece di' ErrorObserver' nella funzione 'subscribe'. – Gabriel

+0

stesso qui, questo non chiama il caso di gestione osservabile fallito – sam

1

È necessario utilizzare .subscribe il observable per registrare success, error & completed callback

Codice

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 
} 
+0

Errore: (105, 16) TS2322: Tipo 'Sottoscrizione ' non è assegnabile al tipo 'Osservabile '. La 'fonte' di proprietà è mancante nel tipo 'Abbonamento '. – user3725805

+0

La posizione (105,16) è questa nella seconda riga – user3725805

2

Andando oltre il codice sorgente a node_modules\@angular\http\testing\mock_backend.d.ts. MockConnection.mockRespond è già nel tuo codice. MockConnection.mockError è quello che potrebbe essere necessario. Gioca con esso e guarda cosa ottieni.

+0

Scusate per il downvote su questo, dopo aver attraversato le definizioni il modo per farlo funzionare era in effetti utilizzare il mockError con una classe di errore personalizzata – amay0048

37

Per ottenere il funzionamento di errore finto, è necessario importare ResponseType da @ angolare/http e includono il tipo di errore nella risposta finto, quindi estendere Response e implementare errore

import { Response, ResponseOptions, ResponseType, Request } from '@angular/http'; 
import { MockConnection } from '@angular/http/testing'; 

class MockError extends Response implements Error { 
    name:any 
    message:any 
} 

... 
handleConnection(connection:MockConnection) { 
    let body = JSON.stringify({key:'val'}); 
    let opts = {type:ResponseType.Error, status:404, body: body}; 
    let responseOpts = new ResponseOptions(opts); 
    connection.mockError(new MockError(responseOpts)); 
} 
+0

Grazie [amay0048] (http://stackoverflow.com/users/3145286/amay0048), ho visto la soluzione sul [problema github] (https://github.com/angular/angular/pull/8961). Questo sta funzionando per me. –

+0

Questa soluzione funziona perfettamente! – Intrepid

+0

Grazie MAN. mi ha salvato. –

Problemi correlati