angularjs - Mocking a service call from a controller, Jasmine using the actual service -
i've trying test service called controller using spy , mock. jasmine's error appear it's trying call actual service? doing wrong?
controller
angular.module('vsapp').controller('kitsctrl', function ($scope, productsdataservice) { productsdataservice.getproducts("kit").success(function (data) { $scope.products = data; }); });
spec
describe("kits controller", function () { var productsdataservicemock, $controllerconstructor, scope; beforeeach(module('vsapp')); beforeeach(inject(function ($controller, $rootscope) { $controllerconstructor = $controller; scope = $rootscope.$new(); productsdataservicemock = { getproducts: function(type) {return {};} }; })); it('should call products data service', inject(function () { var ctrl = $controllerconstructor('kitsctrl', {$scope: scope, productsdataservice: productsdataservicemock}); spyon(productsdataservicemock, 'getproducts').andcallthrough(); expect(productsdataservicemock.getproducts).tohavebeencalled(); })); });
error
typeerror: 'undefined' not function (evaluating 'productsdataservice.getproducts("kit").success(function (data) { $scope.products = data; })') @ /**removed**/public/app/controllers/kitsctrl.js:9
there 2 mistakes in test:
- you spy on mock after having constructed controller, , after controller has called mock.
- the controller expects service return object having
success()
method, mock returns empty object. so, when callingsuccess()
, since method doesn't exist, exception thrown.
my advice: don't create mock. spy on real service, , use real promise api rather soon-to-be-deprecated success/error callbacks:
angular.module('vsapp').controller('kitsctrl', function ($scope, productsdataservice) { productsdataservice.getproducts("kit").then(function (data) { $scope.products = data; }); });
and
var $controller; beforeeach(inject(function (_$controller_, $rootscope) { scope = $rootscope.$new(); $controller = _$controller_; })); it('should call products data service', inject(function(productsdataservice, $q) { spyon(productsdataservice, 'getproducts').andreturn($q.when('somedata')); $controller('kitsctrl', {$scope: scope}); expect(productsdataservicemock.getproducts).tohavebeencalledwith('kit'); expect($scope.products).tobe('somedata'); }));
Comments
Post a Comment