【问题标题】:how to mock http error for angular2 testing如何模拟 angular2 测试的 http 错误
【发布时间】:2016-02-16 15:19:24
【问题描述】:

我正在为 angular2 服务编写单元测试。代码sn-ps:

// 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 为空。

【问题讨论】:

    标签: angular unit-testing typescript angular2-http


    【解决方案1】:

    要使模拟错误正常工作,您需要从 @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));
    }
    

    【讨论】:

    • 感谢amay0048,我在github issue 上看到了您的解决方案。这对我有用。
    • 谢谢男人。救了我。
    • 您可以将Response 转换为响应和错误的union type,而不是创建MockError 类,即connection.mockError(new Response(responseOpts) as Response &amp; Error);
    • @msdedwards TS 中的工会在我第一次写这篇文章时有点糟糕,但我想说今天这是最好的选择。
    • 使用 Angular 6... 就足够了:connection.mockError(new HttpErrorResponse({ status: 404, error: 'No Such Object'})); 使用 import { HttpErrorResponse } from '@angular/common/http';
    【解决方案2】:

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

    【讨论】:

    • 很抱歉对此投了反对票,在通过定义之后,让这个工作的方法确实是使用带有自定义错误类的 mockError
    【解决方案3】:

    为我工作:

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

    【讨论】:

    • 对我不起作用,这在subscribe 函数中触发了NextObserver 而不是ErrorObserver
    • 这里也一样,这不会调用失败的observable处理案例
    猜你喜欢
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 2017-04-19
    • 2017-09-30
    • 2017-03-14
    • 2016-06-28
    • 1970-01-01
    • 2016-04-18
    相关资源
    最近更新 更多