如何为angular2测试模拟http错误

how to mock http error for angular2 testing

我正在为 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
})));

我的服务:

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

第一个expect就OK了,程序进入map调用,而不是catch。但是如何获取状态码 404 呢? res.status 为空。

查看 node_modules\@angular\http\testing\mock_backend.d.ts 处的源代码。 MockConnection.mockRespond 已经在您的代码中。 MockConnection.mockError 是您可能需要的。 试一试,看看你得到了什么。

适合我:

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

要使模拟错误正常工作,您需要从@angular/http 导入 ResponseType 并将错误类型包含在模拟响应中,然后扩展 Response 并实现 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));
}