我已经创建了一个服务来充当我的后端API的客户端。当后端返回错误时,我的服务应该通过重新抛出错误来处理该问题,并使用更可读的消息稍后在控制器级别捕获:
function readApi() {
return $http.get("adress").catch(function (e) {
if (e.status === 400) {
throw new Error("API call not succeded...");
}
}).then(function (requestResult) {
// further processing of result
});
}
然后,我尝试在Jasmine中编写一个测试此行为的规范:
it('throw proper error for 400 reponse from API', function () {
httpBackend.expectGET('address').respond(400, '');
expect(function () {
myService.readApi();
}).toThrow();
httpBackend.flush();
});
afterEach(function () {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
不幸的是,错误似乎是从httpBackend.flush()而不是我的函数引发的,导致测试失败。
使用它是错误的还是在httpBackend mock中出错?我该如何进行这样的测试呢?
修改
我尝试了@ tomepejo的答案,几乎工作了:
it('throw proper error for 400 reponse from API', function () {
httpBackend.expectGET('address').respond(400, '');
expect(function () {
myService.readApi();
httpBackend.flush();
}).toThrow();
});
afterEach(function () {
//httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
不幸的是,在每个人的身体出现错误后会发生错误:
Error: [$rootScope:inprog] $digest already in progress
http://errors.angularjs.org/1.3.14/$rootScope/inprog?p0=%24digest
at .../Scripts/Lib/angular.js:63:12
at beginPhase (.../Scripts/Lib/angular.js:14755:15)
at Scope.$digest (.../Scripts/Lib/angular.js:14197:9)
at Function.$httpBackend.verifyNoOutstandingExpectation (.../Scripts/Lib/angular-mocks.js:1550:38)
at Object.<anonymous> (.../ApiClientTest.js:94:29)
我认为它不需要提及,这个afterEach在许多其他测试中很有用,并且在每次测试结束时粘贴这些调用(或者将异常测试提取到另一个测试中)并不像那样这样做的方法。
或许这是一个角度模拟库中的错误,我应该提交错误报告?
答案 0 :(得分:1)
您可以通过将 false 传递给verifyNoOutstandingExpectation()
函数来实现您想要的效果,但为了不干扰其他测试的$ digest循环,您可以执行以下操作: / p>
var shouldDigest;
beforeEach(inject(function (...) {
//your initialization here
shouldDigest = true;
}));
afterEach(function () {
httpBackend.verifyNoOutstandingExpectation(shouldDigest);
httpBackend.verifyNoOutstandingRequest();
});
并在此测试中具体说明:
it('throw proper error for 400 reponse from API', function () {
httpBackend.expectGET('address').respond(400, '');
expect(function () {
myService.readApi();
httpBackend.flush();
}).toThrow();
shouldDigest = false;
});
此处的来源和解释:http://nikas.praninskas.com/angular/2015/11/20/quickie-httpbackend-digest-in-progress/
答案 1 :(得分:0)
尝试将httpBackend.flush()
置于期望函数内。
expect(function () {
myService.readApi();
httpBackend.flush();
}).toThrow();