Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...