【问题标题】:Jasmine - Mocked method can't be foundJasmine - 找不到模拟方法
【发布时间】:2014-05-05 09:19:37
【问题描述】:

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

【问题讨论】:

  • 你能发表评论吗?这是一项服务吗?如果是这样,它返回一个对象而不是函数

标签: javascript angularjs jasmine


【解决方案1】:

如果 Comment 是一项服务,我会这样模拟它:

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

但实际上我根本不会这样嘲笑它。我会允许将服务注入到单元测试中,然后使用 jasmine 的 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

【讨论】:

  • 我认为您的第一个建议一开始也可以,但后来$scope.newComment = new Comment(); 不再有效,因为 CommentMock 不是对象构造函数。注入实际的服务 Comment 是可行的,但我认为因为我正在编写单元测试,所以它们应该尽可能地隔离。通常不应该模拟或存根依赖项吗?
  • 我们在嘲笑他们,但通过控制他们返回的内容。这是我们现在一直在使用的方法,过去几个月我在 Angular 单元测试中工作。为什么要重新创建您想在测试中使用的代码 - 测试原始代码!
  • 此外,当您测试控制器时,我假设您并不关心评论服务的功能 - 这在其他地方进行了测试,并且当您将其注入控制器时假定它可以正常工作使用。
  • 这是有道理的。我将andCallThrough() 更改为andCallFake(),这样我就可以在不依赖评论服务的情况下模拟异步功能。非常感谢!这帮了很多忙!
  • 别担心,伙计!我已经写了一些关于单元测试最佳想法的不同问题和答案......我会将链接放在我的答案中
猜你喜欢
  • 1970-01-01
  • 2018-10-21
  • 2017-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-02
  • 2017-03-17
  • 2020-03-21
相关资源
最近更新 更多