Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

javascript - 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;
        },
     };
  }]);

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...