Undefined Is Not An Object In Angular.js Service
I have a method like this in my service angular.module('App') .factory('AppService', [function() { var _admin; return { get admin() { return _admin;
Solution 1:
In your beforeEach you would inject the service like this
varAppService;
beforeEach(inject(function(_AppService_) {
AppService = _AppService_;
}));
and in your test you can mock using jasmine like this
spyOn(AppService, 'getAdmin').andCallFake(function() {
// return whatever you want
return 0;
});
// then the expect would be likeexpect(AppService.getAdmin).toHaveBeenCalled();
More about jasmine's spies http://jasmine.github.io/2.0/introduction.html#section-Spies
Solution 2:
I think this is what are you looking for:
(function() {
"use strict";
angular.module('app', [])
.controller('mainCtrl', function(AppService) {
var vm = this;
vm.service = AppService;
vm.service._admin = 10;
vm.random = function() {
vm.service._admin = Math.floor(Math.random() * 5);
console.log('AppService obj => ', AppService._admin);
};
})
.factory('AppService', function() {
var admin;
this.appService = {
get_admin() {
return admin;
},
set_admin(val) {
admin = val;
}
};
returnthis.appService;
});
})();
<!DOCTYPE html><htmlng-app="app"><head><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script></head><bodyng-controller="mainCtrl as main"><buttontype="button"ng-click="main.random()">Change value</button><spanng-bind="main.service._admin"></span></body></html>
Post a Comment for "Undefined Is Not An Object In Angular.js Service"