我有一个控制器和服务,我已经写了一些单元测试。该服务执行http
请求,控制器有.then
和.catch
阻止。我可以测试.then
阻止没有问题,但是如何测试.catch
?
控制器:
$scope.performPost = function (action) {
$scope.shoppingCart = function() {
$scope.loading = true;
$scope.acText = '';
myService.postAction('cart', $scope.myData)
.then(function(data) {
$timeout(function(){
$scope.loading = false;
$scope.tick = true;
}, 1500);
})
.catch(function() {
$scope.errorException();
});
};
switch(action) {
case "viewShoppingCart":
$scope.shoppingCart();
break;
case "updateProfile":
$scope.updateUserDetails();
break;
}
};
测试.then:
describe("MyController Tests", function() {
var scope;
var ctrl;
var customer = {
"accountId" : "12345678901",
"firstName" : "Joe",
"lastName" : "Bloggs",
};
var unlockRespone = {};
beforeEach(inject(function($rootScope, $controller, myService, _$q_, $httpBackend, $timeout) {
scope = $rootScope.$new();
rootScope = $rootScope;
mockMyService = myService;
pingUrl = "http://server:80/ping";
httpBackend = $httpBackend;
timeout = $timeout;
var unlockDeferred = _$q_.defer();
unlockDeferred.resolve(unlockRespone);
spyOn(mockMyService, 'postAction').and.returnValue(unlockDeferred.promise);
spyOn(rootScope, '$broadcast').and.callThrough();
ctrl = $controller('MyController', {$scope:scope, myService:mockMyService});
spyOn(scope, 'performPost').and.callThrough();
}));
it("Should call the viewShoppingCart function", function() {
httpBackend.expectGET(pingUrl).respond({ status: "OK" });
scope.performPost('viewShoppingCart');
timeout.flush(4000);
expect(scope.loading).toBeFalsy();
expect(scope.tick).toBeTruthy();
});
});
答案 0 :(得分:1)
您可以将$或其他错误状态传递给$ httpBackend的response方法作为第一个参数。
it("Should call errorException", function() {
spyOn(scope, 'errorException');
httpBackend.expectPOST('shopping-cart-url').respond(500, '');
scope.performPost('viewShoppingCart');
httpBackend.flush();
expect(scope.errorException).toHaveBeenCalled();
});
答案 1 :(得分:1)
describe("MyController Tests", function() {
var scope;
var ctrl;
var $q;
var customer = {
"accountId" : "12345678901",
"firstName" : "Joe",
"lastName" : "Bloggs",
};
var response = {};
beforeEach(inject(function($rootScope, $controller, myService, _$q_, $httpBackend, $timeout) {
scope = $rootScope.$new();
rootScope = $rootScope;
mockMyService = myService;
pingUrl = "http://server:80/ping";
httpBackend = $httpBackend;
timeout = $timeout;
$q = _$q_;
spyOn(rootScope, '$broadcast').and.callThrough();
ctrl = $controller('MyController', {$scope:scope, myService:mockMyService});
spyOn(scope, 'performPost').and.callThrough();
}));
it("calls then", function() {
var deferred = $q.defer();
deferred.resolve(response);
spyOn(mockMyService, 'postAction').and.returnValue(deferred.promise);
// test code for then
});
it("calls catch", function() {
var deferred = $q.defer();
deferred.reject(response);
spyOn(mockMyService, 'postAction').and.returnValue(deferred.promise);
// test code for catch
});
});