Angular $ httpBackend如何模拟错误响应?

Tig*_*Too 8 unit-testing angularjs

我正在尝试测试我的程序正确处理我从http请求中获得的错误消息,但我无法弄清楚如何使用$ httpBackend来模拟它.鉴于以下内容:

$httpBackend.expectGET(path).respond(400, object);
Run Code Online (Sandbox Code Playgroud)

400集response.status和对象设置response.data,但是如何设置response.error?我需要测试的数据不在数据字段中.

示例API响应:

{
    status: 400,
    data: {},
    error: {}
}
Run Code Online (Sandbox Code Playgroud)

dan*_*y74 4

代码 ...

$httpBackend.expectGET(path).respond(400, object);
Run Code Online (Sandbox Code Playgroud)

意思是当代码向“路径”端点发出请求时,以 400 状态代码和响应“对象”进行响应

因此,例如,假设您的单元测试在您的应用程序中命中了此代码......

$http.GET(path).then(function(response) {
    // this code is hit with 2xx responses
    vm.fred = 'hello';
}).catch(function(errorResponse) {
    // this code is hit with any status code not starting with 2! e.g. 400
    vm.fred='failed';
});
Run Code Online (Sandbox Code Playgroud)

因此,您的代码将导致 catch 块被执行。但是,在单元测试中,要强制执行 catch 块,您需要执行以下操作...

$rootScope.$digest();
Run Code Online (Sandbox Code Playgroud)

这将触发 then 或 catch 块的执行(以相关者为准)。

然后您可以像往常一样在单元测试中做出期望。请注意,在您的示例中,errorResponse 将是对象。