Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to mock http error for angular2 testing

Tags:

I am writing unit tests for an angular2 service. Code snippets:

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

my Service:

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

The first expect is OK, the program goes into the map call, not the catch. But how do I get the status code 404? res.status is null.

like image 718
Galdor Avatar asked Feb 16 '16 15:02

Galdor


1 Answers

To get the mock error working, you need to import ResponseType from @angular/http and include the error type in the mock response, then extend Response and implement Error

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)); } 
like image 122
amay0048 Avatar answered Oct 06 '22 06:10

amay0048