how to mock http error for angular2 testing

20,020

Solution 1

works for me:

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

Solution 2

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

Solution 3

Going over the source code at node_modules\@angular\http\testing\mock_backend.d.ts. MockConnection.mockRespond is already in your code. MockConnection.mockError is what you may need. Play with it and see what you get.

Share:
20,020

Related videos on Youtube

Galdor
Author by

Galdor

Updated on July 28, 2020

Comments

  • Galdor
    Galdor almost 4 years

    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.

  • amay0048
    amay0048 over 7 years
    Sorry for the downvote on this, after going through the definitions the way to get this working was indeed to use the mockError with a custom error class
  • Alexis Cramatte
    Alexis Cramatte over 7 years
    Thanks amay0048, I've seen your solution on the github issue. This is working for me.
  • Human Being
    Human Being about 7 years
    Thanks MAN. saved me.
  • Gabriel
    Gabriel about 7 years
    Did not work for me, this triggered the NextObserver instead of ErrorObserver in the subscribe function.
  • sam
    sam about 7 years
    same here , this does not call the failed observable handling case
  • msdedwards
    msdedwards almost 7 years
    Instead of creating the MockError class you can cast a Response to the union type of Response and Error i.e. connection.mockError(new Response(responseOpts) as Response & Error);
  • amay0048
    amay0048 almost 7 years
    @msdedwards Unions in TS were a bit whack when I first wrote this, but I would say that today this is the best option.
  • lealceldeiro
    lealceldeiro about 6 years
    Using Angular 6... it would be good enough to do: connection.mockError(new HttpErrorResponse({ status: 404, error: 'No Such Object'})); by using import { HttpErrorResponse } from '@angular/common/http';
  • amay0048
    amay0048 about 6 years
    @lealceldeiro for sure, i think \@angular had only just been released when I wrote this