茉莉花 - 模拟方法无法找到

时间:2014-05-05 09:19:37

标签: javascript angularjs jasmine

在Jasmine测试中,我有以下内容:

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

但是,我收到此错误: Failure/Error: save() method does not exist

在Angular控制器中我有这个:

$scope.newComment = new Comment();

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

    Comment.save( $scope.newComment )
      .$promise
      .then(
        function() {
          // success stuff
        },
        function() {
          // error junk
        }
      );
  }
};

1 个答案:

答案 0 :(得分:3)

如果评论是一项服务,我会嘲笑它:

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

但实际上我根本就不会这样嘲笑它。我会允许将服务注入单元测试,然后使用茉莉花的spyOn方法拦截服务调用。

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 
  }

}

代码是超级简化的,不会像这样直接工作,但它的整体想法......

我写的其他一些单元测试链接:

Mocking Controller Instantiation In Angular Directive Unit Test

Unit testing in AngularJS - Mocking Services and Promises