25

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

第一个期望是可以的,程序进入 map 调用,而不是 catch。但是如何获得状态码 404?res.status 为空。

4

3 回答 3

37

要使模拟错误正常工作,您需要从 @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));
}
于 2016-10-05T00:06:43.637 回答
2

浏览源代码node_modules\@angular\http\testing\mock_backend.d.tsMockConnection.mockRespond已经在您的代码中。 MockConnection.mockError是您可能需要的。玩它,看看你会得到什么。

于 2016-06-15T15:56:35.813 回答
0

为我工作:

    mockConnection.mockRespond (new Response (new ResponseOptions ({
        body: {},
        status: 404
    })));
于 2016-07-12T11:32:26.020 回答