Thursday, 15 September 2011

javascript - Mocking Jasmine Promises -



javascript - Mocking Jasmine Promises -

i trying write jasmine unit tests test angular controllers , running issues service has been injected , returning promise.

i have service retrieves info server:

app.factory('lookupservice', ['$resource', '$http', '$cookies', function ($resource, userid) { homecoming $resource('./controller/getfunction', {}, { query: { method: 'get', params: { userid: userid }, isarray: true } }); }]);

which called in controller:

$scope.returneddatastore = lookupservice.get({ userid: $scope.userid }); $scope.returneddatastore.$promise.then(function (result) { $scope.processdata(result.data); });

in unit tests injecting service below:

beforeeach(function () { module('app'); lookupservice = jasmine.createspyobj('lookupservice', ['get']); inject(function ($rootscope, $controller, $q) { $scope = $rootscope.$new(); var deferred = $q.defer(); lookupservice.get.and.returnvalue(deferred.promise); ctrl = $controller('mycontroller', { $scope: $scope, lookupservice: lookupservice }); }); });

however, when service called in controller, receiving error indicates $scope.returneddatastore.$promise undefined:

cannot read property 'then' of undefined

i've searched lot seek resolve issue i'm not having much luck.

i'd appreciative if point me in right direction!

what -

handle promise in service , homecoming promise object controller, see if helpful you:

describe('controller: mainctrl', function() { beforeeach(module('myapp')); var mainctrl, scope, someservice, spygetsomething; beforeeach(inject(function($controller, $rootscope) { someservice = { getsomething: function() {} }; spygetsomething = spyon(someservice, 'getsomething').andreturn({ then: function() {} }); mainctrl = $controller('mainctrl', { $scope: scope, someservice: someservice }); }); ... it('should phone call someservice.getsomething() ', function() { expect(spygetsomething).tohavebeencalled(); }); });

(note: didn't test it)

javascript angularjs unit-testing jasmine promise

No comments:

Post a Comment