undefined不是Angular.js服务中的对象

时间:2016-07-06 15:22:03

标签: javascript angularjs mocha karma-mocha

我的service

中有这样的方法
 angular.module('App')
  .factory("AppService", [function() {

    var _admin;

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

在我的controller我正在使用它:

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

当我尝试测试function时,我收到如下错误:

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');
});

我也不确定如何模仿AppServiceget方法的set

2 个答案:

答案 0 :(得分:0)

在你的beforeEach中,你会像这样注入服务

var AppService;
 beforeEach(inject(function(_AppService_) {
   AppService = _AppService_;
}));

在你的测试中你可以像这样使用茉莉花来模拟

spyOn(AppService, 'getAdmin').andCallFake(function() {
  // return whatever you want
        return 0;
  });


// then the expect would be like
expect(AppService.getAdmin).toHaveBeenCalled();

更多关于茉莉花的间谍http://jasmine.github.io/2.0/introduction.html#section-Spies

答案 1 :(得分:0)

我认为这就是你在寻找的东西:

(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>