AngularJS 单元测试 element.bind

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

在由 data-type-ahead 调用的我的指令内,我在一系列事件中执行以下操作:

$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$触发事件后申请

最佳答案

您有两种方法可以使其发挥作用。第一个是向您的方法添加超时 ( 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 方法是否创建了绑定(bind),您可以测试 $element.bind (通过 spy On(element, 'bind'))。

关于AngularJS 单元测试 element.bind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34413174/

相关文章:

javascript - 如何使用 img 元素将数据与 angularJS 绑定(bind)

javascript - Angular 代码在移动到模板文件时停止工作

javascript - Angular js + 选择插件 + 将值设置为在下拉列表中选择

unit-testing - 没有找到测试。确保已安装的测试发现器和执行器、平台和框架版本设置正确,然后重试

unit-testing - 测试 AngularJS 范围变量

javascript - 更改文本区域模型后指令不会触发

MYSQL 的 PHP 脚本作用于一个文件,而不作用于另一个文件

php - 使用相同的 PHPUnit 测试用例测试多个类

angularjs - 如何根据 bootstrap 网格系统使用 angularjs 指令设置 height = width 以获得方形 div?

javascript - Controller 数据未传递给指令