【问题标题】:AngularJS Unit Test element.bindAngularJS 单元测试 element.bind
【发布时间】:2015-12-22 10:06:23
【问题描述】:

data-type-ahead 调用的我的directive 中,在一系列事件中,我有以下内容:

$scope.test = 5;

// Bind blur event and clear the value of 
element.bind('blur', function(){
    $scope.test = 0;
});

我已尝试在单元测试中使用多种方法来正确测试此blur 事件的功能,但我没有成功。我见过提到函数triggerHandler。这是我在单元测试中的尝试:

//Inject $compile and $rootScope before each test.
beforeEach(inject(function(_$compile_, _$rootScope_) {
    $compile = _$compile_;
    $rootScope = _$rootScope_;

    $scope = $rootScope.$new();
    $scope.test = 5

    html = angular.element('<input type="text" data-type-ahead/>');

    //Apply $scope to directive html.
    directive = $compile(html)($scope);

    //Trigger digest cycle.
    $scope.$digest();
}));

it('should trigger the events bound to the blur event on the directive', function() {
    html.triggerHandler('blur')
    expect($scope.test).toEqual(0);
});

但是这失败了,因为$scope.test 仍保留在 5 上。是 html 元素不正确,在我触发事件后是否需要另一个 $digest$apply

【问题讨论】:

    标签: angularjs unit-testing angularjs-directive karma-jasmine


    【解决方案1】:

    您有 2 种方法可以让它发挥作用。首先是为您的方法添加超时 (docs):

    // somewhere above add - 
    var originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
    
    // in your beforeEach
    
    beforeEach(function(){
     html.triggerHandler('blur');
      setTimeout(function(){
      done();
     }, 1000);
    });
    
    it('should trigger the events bound to the blur event on the directive',  
       function() {
        expect($scope.test).toEqual(0);
       }
    );
    

    我认为这是“不太好”的做法(坏或坏对于测试来说太消极了——当你测试的那一刻,你已经变得更好了 :))。一般来说,我尽量避免测试异步,因为最终我的方法(也称为单元)在内部是同步的。

    “更好的做法”是编写改变值的方法,如下所示:

    // in the directive's ctrl
    this.changeValue = function changeValue{
      $scope.test = 0;
    }
    
    // later on set the watcher
    // Bind blur event and clear the value of 
    $element.bind('blur', this.changeValue);
    

    然后测试方法本身而不是异步测试它。如果您希望看到您的 ctrl/link 方法创建了绑定,您可以测试 $element.bind(通过 spyOn(element, 'bind'))。

    【讨论】:

      猜你喜欢
      • 2013-05-27
      • 2018-07-06
      • 2015-07-04
      • 2013-08-29
      • 2013-04-06
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多