如何检查我的元素是否已集中在单元测试中

Maa*_*ten 18 unit-testing jasmine angularjs

我有以下指令来自动对焦字段:

.directive('ngAutofocus', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elm) {
                $timeout(function () {
                elm[0].focus();
            });
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

我该如何对此进行单元测试?我尝试了几个像下面的选择器,但它们都返回错误或错误:

console.log($(elm[0]).is(':focus'));
Run Code Online (Sandbox Code Playgroud)

我的单元测试设置如下:

elm = angular.element('<input type="text"  name="textfield1" ng-autofocus>');
$scope.$digest();
$compile(elm)($scope);
Run Code Online (Sandbox Code Playgroud)

Maa*_*ten 34

我明白了,实际上很明显;

it('should set the focus on timeout', function () {
    spyOn(elm[0],'focus');
    $timeout.flush();
    expect(elm[0].focus).toHaveBeenCalled();
})
Run Code Online (Sandbox Code Playgroud)

我的问题有两方面:

  1. 我没有调用超时刷新功能,因此没有发生超时,并且
  2. 我试图查看元素的焦点属性,而只是查看focus()函数的调用更像是单元测试.焦点属性实际上属于e2e测试区域.


Han*_*sen 5

您可以用来document.activeElement检查焦点。唯一的缺点是需要将 HTML 添加到文档正文中才能正常工作。

https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement