Initially, my Controller looks like this:
login.controller.js:
angular.module('app').controller('LoginController',
function($scope,UserService,$location) {
$scope.submit = function() {
UserService.login(email,password).then(function(data){
if(data.result=='success'){
$location.path('/home');
else{
$scope.loginError='Login failed';
}
},function(error){
$scope.loginError='Login failed';
});
};
Next, I have a factory service called UserService.js
angular.module('app').factory('UserService', function($http,$q,CONST) {
login: function(username, password) {
var defer =$q.defer();
$http({
method:'POST',
url:CONST.baseUrl+'rest/login',
data:{
userName:username,
password:password
}
}).success(function(data,status,headers,config){
defer.resolve(data);
}).error(function(data){
defer.reject(data);
});
return defer.promise;
},
Afterwards, my Jasmine test is structured like this:
describe('testing the userService',function(){
beforeEach(module('app'))
var scope,LoginController,httpBackend;
beforeEach(inject(function(_$rootScope_,$controller,_UserService_,_$httpBackend_){
scope = _$rootScope_.$new();
httpBackend = _$httpBackend_;
LoginController = $controller('LoginController',{
$scope:scope,
UserService:_UserService_
});
}));
it('should return success when logging in',function(){
httpBackend.expectPOST('rest/login',{
userName:'Jordan',
password:'password'
}).respond(200,{result:'success'});
spyOn(UserService,'login').and.callThrough();
scope.submit();
httpBackend.flush();
expect(UserService.login).toHaveBeenCalled();
expect(location.path()).toBe('/home');
});
afterEach(function(){
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
});
However, the test result indicates:
Chrome 43.0.2357 (Windows 7 0.0.0) testing the userService should return success when logging in FAILED
Expected spy login to have been called.
at Object.<anonymous> (C:/Users/IBM_ADMIN/desk/workspace/WaterFundWeb/WebContent/test/unit/userService.js:28:29)
I am certain that the login() function is being called, so why did the test fail?