如何在控制器范围内测试由事件执行的函数



控制器功能:

angular.module('myApp').controller('MyController', function(){
   $scope.f = function($event){
      $event.preventDefault();
      //logic
      return data;
   }
})
describe('MyController', function(){
    'use strict';
    var MyController,
        $scope;
    beforeEach(module('myApp'));
    beforeEach($inject(function($rootScope, $controller){
       $scope = $rootScope.$new();
       MyController = $controller('MyController', {
          $scope: $scope
       })
    }));
})
it('should...', function(){
    //fire event and expect data
})

指令中使用$scope.f函数,可由ng-click="f($event)"

执行。

单元测试中火灾事件的正确方法是什么?

简短回答

你不需要触发事件。您可以访问作用域,其中包含要测试的函数。这意味着您只需执行函数,然后断言。它看起来像这样:

it('should call preventDefault on the given event', function(){
  var testEvent = $.Event('someEvent');
  $scope.f(testEvent);
  expect(testEvent.isDefaultPrevented()).toBe(true);
});

参见以下内容:

    jQuery事件对象
  • event.isDefaultPrevented ()

完整规范

另外-您的it块应该在您的describe块内,以便它可以访问$scope字段。它看起来应该像这样:

describe('MyController', function(){
  'use strict';
  var MyController,
      $scope;
  beforeEach(module('myApp'));
  beforeEach($inject(function($rootScope, $controller){
    $scope = $rootScope.$new();
    MyController = $controller('MyController', {
      $scope: $scope
    })
  }));
  it('should call preventDefault on the given event', function(){
    var testEvent = $.Event('someEvent');
    $scope.f(testEvent);
    expect(testEvent.isDefaultPrevented()).toBe(true);
  });
})

关于结构

不要害怕使用describe块来构建您的测试。假设您在$scope上有另一个名为f2的函数,那么您可能希望对spec文件进行如下划分:

describe('MyController', function(){
  'use strict';
  var MyController,
      $scope;
  beforeEach(module('myApp'));
  beforeEach($inject(function($rootScope, $controller){
    $scope = $rootScope.$new();
    MyController = $controller('MyController', {
      $scope: $scope
    })
  }));
  describe('$scope', function() {
    describe('.f()', function() {
      // tests related to only the .f() function
    });
    describe('.f2()', function() {
      // tests related to only the .f2() function
    });
  });
})

这样做的好处是,当测试失败时,您看到的错误消息是基于describe块的层次结构构建的。所以它应该是这样的:

MyController $scope .f()应该调用preventDefault事件

最新更新