gpt4 book ai didi

angular - 如何为angular2测试模拟http错误

转载 作者:太空狗 更新时间:2023-10-29 16:51:45 26 4
gpt4 key购买 nike

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

最佳答案

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

关于angular - 如何为angular2测试模拟http错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35436261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com