如何模拟angular2测试的http错误

时间:2016-02-16 15:19:24

标签: angular unit-testing typescript angular2-http

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

第一个期望是好的,程序进入地图调用,而不是捕获。但是如何获取状态代码404? res.status为null。

4 个答案:

答案 0 :(得分:36)

要使模拟错误起作用,您需要从@ angular / http导入ResponseType并在模拟响应中包含错误类型,然后扩展Response并实现错误

{{1}}

答案 1 :(得分:2)

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

答案 2 :(得分:1)

您需要在.subscribe上使用observable来注册successerror&amp; completed回拨

<强>代码

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
}

答案 3 :(得分:0)

适合我:

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