I'm learning angularJS unit-testing and I'm struggling unit testing a basic "login" function on an "AuthenticationService" service.
The service method uses $q.defer()
to set up a promise and then rejects or resolves it based on input.
How do I spy on or otherwise test that promise?
What is wrong with the below? The test fails - error is "undefined" rather than 'AuthenticationService.login - missing argument'
Hopefully it is obvious what I am trying to do, I can't really put it into words.
The Service
angular.module('moduleName').factory('AuthenticationService', function($q, $http) {
var serviceObject = {
login = function(credential, password) {
var d = $q.defer();
// check if any fields are missing
if (!credential && !password || credential === '' || password === '') {
d.reject('AuthenticationService.login - missing argument');
} else {
var sacho = {message: "I'm so confused"};
d.resolve(sacho);
}
return d.promise;
}
}
};
return serviceObject;
});
The Test
describe('AuthenticationService', function()
{
var scope, AuthenticationService, $httpBackend;
beforeEach(inject(function($rootScope, _AuthenticationService_, _$httpBackend_) {
scope = $rootScope.$new();
AuthenticationService = _AuthenticationService_;
MemberLookup = _MemberLookup_;
$httpBackend = _$httpBackend_;
}));
describe('Logging In', function() {
it('promise should be rejected if any fields are empty', function() {
AuthenticationService.login('','').catch(function(error){
expect(error).toEqual('AuthenticationService.login - missing argument');
});
});
});
});
EDIT: AuthenticationService.login
returns a promise.
The promise should be rejected if either of the credentials to the method are blank or missing.
In the test code (below) I have tried to write a test to see if the promise is rejected. The test inputs blank strings as arguments to the AuthenticationService.login
method. The expected behaviour is the promise being rejected with the string 'AuthenticationService.login - missing argument'
. However, running the test fails - Authentication.Service.login('','').catch
's callback does not work as expected.
I have also tried using .then(null, callback)
.
How do I spy on the promise returned by AuthenticationService.login
when given specific
parameters?