angularjs – Angular $httpBackend如何模拟错误响应?
发布时间:2020-12-17 07:11:03 所属栏目:安全 来源:网络整理
导读:我正在尝试测试我的程序正确处理我从http请求中获得的错误消息,但我无法弄清楚如何使用$httpBackend来模拟它.鉴于以下内容: $httpBackend.expectGET(path).respond(400,object); 400集response.status和对象设置response.data,但是如何设置response.error?
我正在尝试测试我的程序正确处理我从http请求中获得的错误消息,但我无法弄清楚如何使用$httpBackend来模拟它.鉴于以下内容:
$httpBackend.expectGET(path).respond(400,object); 400集response.status和对象设置response.data,但是如何设置response.error?我需要测试的数据不在数据字段中. 示例API响应: { status: 400,data: {},error: {} } 解决方法
代码 …
$httpBackend.expectGET(path).respond(400,object); 说当代码向’path’端点发出请求时,用响应’object’响应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'; }); 因此,您的代码将导致执行catch块.但是,在单元测试中,为了强制执行catch块,你需要做… $rootScope.$digest(); 这将触发then或catch块的执行(以相关者为准). 然后,您可以像往常一样在单元测试中做出预期.请注意,在您的示例中,errorResponse将是对象. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |