Search code examples
angularunit-testingtypescriptangular2-http

how to mock http error for angular2 testing


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.


Solution

  • works for me:

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