Question

In a Jasmine test I have the following:

CommentMock = function() {};
CommentMock.prototype.save = function() {
  // stuff
};
spyOn( CommentMock.prototype, 'save' ).andCallThrough();

However, I'm getting this error: Failure/Error: save() method does not exist

In an Angular controller I have this:

$scope.newComment = new Comment();

$scope.processComment = function( isValid ) {
  if ( isValid ) {

    Comment.save( $scope.newComment )
      .$promise
      .then(
        function() {
          // success stuff
        },
        function() {
          // error junk
        }
      );
  }
};
Était-ce utile?

La solution

If Comment is a service I would mock it like this instead:

CommentMock = {}
CommentMock.save = function() {
  // stuff
};
spyOn( CommentMock, 'save' ).andCallThrough();

But actually I wouldnt mock it like this at all. I would allow the service to be injected into the unit test and then intercept the service call using the spyOn method of jasmine.

var Comment, $rootScope, $controller; //... maybe more...

beforeEach(inject(function(_$rootScope_, _Comment_, _$controller_ //,... everything else) {
  $controller = _$controller_;
  $rootScope = _$rootScope_;
  Comment = _Comment_;
}));

function setupController() {

  spyOn(Comment, 'save').andCallThrough();

  controller = $controller('YOURCONTROLLERSNAME', {
   $scope: $scope,
   Comment: Comment 
  }

}

Code is super simplified and wont work straight like this but its the overall idea...

Some other unit testing links I wrote:

Mocking Controller Instantiation In Angular Directive Unit Test

Unit testing in AngularJS - Mocking Services and Promises

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top