设置焦点的测试指令

时间:2017-02-21 22:27:18

标签: angularjs jasmine

指令:

angular
    .module('tdsapp')
    .directive('focus', focus);

focus.$inject = ['$timeout'];

// Used to set focus on element
function focus($timeout) {
    return {
        scope: { focus: '@'},
        link: function (scope, element) {
            scope.$watch('focus',
              function (value) {
                  if (value) {
                      $timeout(function () {
                          element[0].focus();
                          console.log('focus called');
                      });
                  }
              }
            );
        }
    };

测试规格: describe('指令:focus',function(){

var $timeout, element, $scope, $compile;
beforeEach(function () {
    module('tdsapp');

    inject(function (_$timeout_, $rootScope, _$compile_) {
        $timeout = _$timeout_;
        $compile = _$compile_;
        $scope = $rootScope.$new();
    });
});

it('should call focus on element', function () {
    var elm = angular.element('<input type="text" name="second" focus="true" />');

    spyOn(elm[0], 'focus');
    $timeout.flush();
    expect(elm[0].focus).toHaveBeenCalled();
});

});

我查看了AngularJS: how to test directive which gives focus to element?How do I check if my element has been focussed in a unit test,但都没有效果。我得到了期望失败或$ timeout.flush() - 没有要刷新的延期任务。

编辑:

正如我在文中所述 - 以上两个例子不起作用。

0 个答案:

没有答案