My tests are failing because I can't get my promise to resolve. Within my application, I have two essential services:
1- The first service is called ServerApiService and it is responsible for making calls to the server:
angular.module('test').service('serverApiService', ['$http', function($http) {
var self = this;
self.generateRequest = function(actionName, data) {
console.log('request generated');
//Normally returns 'return $http(config);'
};
}]);
2- The second service depends on ServerApiService and it manages solutions, named SolutionService:
angular.module('test').service('solutionService', ['$q', 'serverApiService', function($q, serverApiService) {
var self = this;
self.list = function(account) {
var data = {
id: account.id
};
var deferred = $q.defer();
serverApiService.generateRequest('solutions.list', data).then(function(response) {
var solutions = [];
for(var i = 0; i < response.Items.length; i++) {
var solutionJSON = response.Items[i];
var studyJSON = solutionJSON.Study;
var solution = {};
solution.id = solutionJSON.Id;
var study = {};
study.name = studyJSON.Name;
solution.study = study;
solutions.push(solution);
}
deferred.resolve(solutions);
});
return deferred.promise;
};
}]);
Troubleshooting
I am trying to test the SolutionService module by creating a mock of the ServerApiService, however, I am struggling to get the spy function to return the promise. Here is the relevant test code snippet:
describe('solution service', function () {
var mockServerApiService, solutionSvc;
beforeEach(function() {
module('test');
});
beforeEach(function() {
module(function($provide) {
$provide.service('serverApiService', function($q) {
this.generateRequest = jasmine.createSpy('generateRequest').and.callFake(function(actionName, data) {
var deferred = $q.defer();
deferred.resolve({Items: [
{
Id: '910759',
Study: {
Id: '213123',
Name: 'test'
},
},
{
Id: '4406510',
Study: {
Id: '063294',
Name: 'test2'
},
},
]});
return deferred.promise;
});
});
});
});
beforeEach(inject(function (serverApiService, solutionService) {
mockServerApiService = serverApiService;
solutionSvc = solutionService;
}));
it('should return all the solutions', function(done) {
var account = {};
account.id = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="384c5d4b4c784c5d4b4c165b5755">[email protected]</a>';
solutionSvc.list(account).then(function(solutions) {
expect(solutions.length).toBe(2);
done();
});
expect(mockServerApiService.generateRequest).toHaveBeenCalled();
})
});
Despite setting up the mock service, the 'then' portion in SolutionService is never executed:
serverApiService.generateRequest('solutions.list', data).then(function(response) {
//Never called
});
To see a demonstration of the issue, check out this Plunker link: http://plnkr.co/edit/gMyaOpfczBmt9HhwzI9m?p=preview