typescript 如何模拟 angular2 测试的 http 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35436261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:17:20  来源:igfitidea点击:

how to mock http error for angular2 testing

angularunit-testingtypescriptangular2-http

提问by Galdor

I am writing unit tests for an angular2 service. Code snippets:

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

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.

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

采纳答案by Galdor

works for me:

对我有用:

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

回答by amay0048

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

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

回答by Timathon

Going over the source code at node_modules\@angular\http\testing\mock_backend.d.ts. MockConnection.mockRespondis already in your code. MockConnection.mockErroris what you may need. Play with it and see what you get.

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

回答by Pankaj Parkar

You need to use .subscribeover the observableto register success, error& completedcallback

您需要使用.subscribeobservable注册successerrorcompleted回调

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
}