简体   繁体   中英

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.

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

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.

You need to use .subscribe over the observable to register success , error & completed callback

Code

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
}

works for me:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM