undefined is not an object in Angular.js service

守給你的承諾、 提交于 2019-12-14 03:24:41

问题


I have a method like this in my service

 angular.module('App')
  .factory("AppService", [function() {

    var _admin;

    return {
        get admin() {
          return _admin;
        },
     };
  }]);

In my controller i am using it like this:

$scope.show = function(){
        return AppService.admin === 0 || (AppService.admin !== 0 && AppService.admin === true);
};

When i am trying to test the function, i am getting an error like below:

it('calls the showAutoPay method', function () {
    $scope.show();
    expect($scope.show).to
           .have.been.calledOnce;
    expect(service.admin).to.not.equal(null);
    assert.equal(service.admin, '0');
});

I am also not sure how to mock the AppService which has the get and set methods.


回答1:


In your beforeEach you would inject the service like this

var AppService;
 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 like
expect(AppService.getAdmin).toHaveBeenCalled();

More about jasmine's spies http://jasmine.github.io/2.0/introduction.html#section-Spies




回答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;
        }
      };

      return this.appService;
    });
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl as main">
  <button type="button" ng-click="main.random()">Change value</button>
  <span ng-bind="main.service._admin"></span>
</body>

</html>


来源:https://stackoverflow.com/questions/38227705/undefined-is-not-an-object-in-angular-js-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!