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

ros*_*eri 5 unit-testing jasmine angularjs karma-jasmine

控制器中的功能:

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
})
Run Code Online (Sandbox Code Playgroud)

$scope.f 函数用于指令,它可以由执行 ng-click="f($event)"

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

Set*_*ers 4

简答

您不需要触发该事件。您可以访问具有您要测试的功能的范围。这意味着您只需执行该函数,然后断言。它看起来像这样:

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

请参阅以下内容:

全规格

另外 - 您的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);
  });
})
Run Code Online (Sandbox Code Playgroud)

关于结构的注释

不要害怕使用describe块来构建测试。$scope想象一下,您在被调用的函数上有另一个函数f2,那么您可能希望将您的规范文件更像这样进行分区:

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
    });
  });
})
Run Code Online (Sandbox Code Playgroud)

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

MyController $scope .f() 应在给定事件上调用 PreventDefault