【问题标题】:how to test function in controller scope executed by event如何在事件执行的控制器范围内测试功能
【发布时间】:2016-08-31 12:53:08
【问题描述】:

控制器中的功能:

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)"执行

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

【问题讨论】:

  • 您能提供更多上下文信息吗?
  • @EvanBechtol 对不起,我希望现在更清楚了

标签: angularjs unit-testing jasmine karma-jasmine


【解决方案1】:

简答

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

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

请参阅以下内容:

完整规格

另外 - 您的 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 的函数,那么您可能希望将您的规范文件分区为更像这样:

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 事件

【讨论】:

    猜你喜欢
    • 2020-12-04
    • 2015-10-12
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多