Lets look at following controller:
angular.module('siteApp')
.controller('RegisterCtrl', function (
$scope,
auth,
$location,
$interval) {
$scope.user = {};
$scope.messages = [];
var success = function(){
$scope.messages.push({
type:'success',
text:'Congratulations,You are registered user!'
});
$interval(function(){$location.path('/login')},6000,1)
}, error =function(){
$scope.messages.push({
type:'danger',
text:'error occurred during registration'
});
};
$scope.save = function(){
auth.register($scope.user).then(success, error);
}
});
The controller uses "auth" service and its "register" method, which sending a request.
We can mock the request with $httpBackend service which test if request is sended.
it('after clicking "save" some request should be sent', function () {
initCtrl()
$httpBackend.expectPOST('/api/register').respond(200, {});
$scope.save();
$httpBackend.flush();
});
Since we trying now to test the logic of the controller (not the service)- I think better practice is to mock the service method and only test if it been called with proper parameters:
it('after clicking "save" auth.register should call', function () {
initCtrl()
spyOn(auth, 'register').andReturn($q.when());
$scope.save();
expect(auth.register).toHaveBeenCalledWith($scope.user);
$scope.$digest(); //important!!!
expect($scope.messages.length).toBe(1)
});
Notice that for testing the messages array you need
$scope.$digest();
statement for update the scope.Hope you have fun reading...
No comments:
Post a Comment