I'm trying to unit test a service that uses a repository which in turn returns a promise to the consumer.
I'm having trouble testing the promise, or I should say I don't know how test the promise.
Any help would be appreciated!
Test.js
var describe = window.describe,
beforeEach = window.beforeEach,
afterEach = window.afterEach,
it = window.it,
expect = window.expect,
inject = window.inject,
module = window.module,
angular = window.angular,
sessionLimitServiceResponse;
describe('Jasmine - SessionLimitService', function () {
beforeEach(module('sessionlimit.module'));
var sessionLimitServiceMock, q;
beforeEach(inject(function (_SessionLimitService_, _SessionLimitResository_, $q) {
sessionLimitServiceMock = _SessionLimitService_;
spyOn(_SessionLimitResository_, "getData").and.returnValue(function () {
var deferred = $q.defer();
deferred.resolve("Remote call result");
return deferred.promise;
});
q = $q;
}));
beforeEach(function () {
sessionLimitServiceMock = {
content: [],
getData: function() {
// mock promise
var deferred = q.defer();
deferred.resolve('foo');
return deferred.promise;
}
};
spyOn(sessionLimitServiceMock, 'getData').and.callThrough();
});
it("Content array must be empty", function () {
expect(sessionLimitServiceMock.content.length).toEqual(0);
});
it('Ensure that the method was invoked', function () {
sessionLimitServiceMock.getData(); // UNSURE OF THIS AS WELL
expect(sessionLimitServiceMock.getData).toHaveBeenCalled();
});
it('Content array must have a value', function() {
sessionLimitServiceMock.getData().then(function(value) {
expect(value).toEqual('foo'); // NOTHING HAPPENS
});
});
});
Service.js
(function (ng, app) {
var sessionLimitRepository = function ($http) {
var repository = {};
repository.getData = function () {
var url = '/' + Techsson.Core.Global.Language + '/api/sessionlimit/getdata';
var result = $http.get(url);
return result;
}
return repository;
};
app.factory('SessionLimitResository', ['$http', sessionLimitRepository]);
}(window.angular, angular.module('sessionlimit.module')));
(function (ng, app) {
var sessionLimitService = function(sessionLimitRepository, $q) {
var service = {};
service.content = [];
service.getData = function () {
var deferred = $q.defer();
if (service.content.length > 0) {
deferred.resolve();
return deferred.promise;
};
var promise = sessionLimitRepository.getData();
promise.success(function(payload) {
service.content.push(payload);
deferred.resolve();
}).error(function() {
deferred.reject();
});
return deferred.promise;
};
return service;
};
app.factory('SessionLimitService', ['SessionLimitResository', '$q', sessionLimitService]);
}(window.angular, angular.module('sessionlimit.module')));
Aucun commentaire:
Enregistrer un commentaire