sourcetip

단위 테스트에서 내 요소가 초점이 맞춰졌는지 확인하려면 어떻게 해야 합니까?

fileupload 2023. 10. 30. 21:13
반응형

단위 테스트에서 내 요소가 초점이 맞춰졌는지 확인하려면 어떻게 해야 합니까?

필드에 자동 초점을 맞추려면 다음과 같은 지침이 있습니다.

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

유닛 테스트는 어떻게 해야 합니까?다음 셀렉터와 같은 몇 가지를 시도해 보았지만 모두 오류나 거짓을 반환합니다.

console.log($(elm[0]).is(':focus'));

장치 테스트는 다음과 같이 설정됩니다.

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

제가 알아냈는데, 사실 꽤 분명했어요.

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

제 문제는 두 가지였습니다.

  1. 타임아웃 플러시 기능을 호출하지 않아서 타임아웃이 발생하지 않았습니다.
  2. 저는 요소의 포커스 속성을 보려고 했는데 포커스() 함수의 호출만 보는 것은 유닛 테스트에 훨씬 가깝습니다.포커스 속성은 실제로 e2e 테스트 영역에 속하는 것입니다.

사용가능document.activeElement초점을 확인합니다.유일한 단점은 HTML을 문서 본문에 추가해야 작동할 수 있다는 것입니다.

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

바로 실행되는 포커스를 테스트(스파이닝)할 수 있는 아래의 보다 상세한 솔루션(즉, 없음)$timeout(또는 기타 이벤트).핵심은 먼저 A를 렌더링하는 것입니다.DOM element전에$compile실행:

'use strict';

describe('Testing the focus call from the link function', function () {

    var $compile;
    var $rootScope;

    beforeEach(angular.mock.module('auto-focus-module'));

    beforeEach(inject(function (_$compile_, _$rootScope_) {

        $compile = _$compile_;
        $rootScope = _$rootScope_;

    }));

    it('should automatically focus when calling the link function', function () {

        var $scope = $rootScope.$new();

        // create an uncompiled DOM element so we can bind the focus spy
        var rawEl = angular.element('<input auto-focus-directive>');

        // set the spy
        spyOn(rawEl[0], 'focus');

        // compile the rawEl so that compile and link functions run
        $compile(rawEl)($scope);

        expect(rawEl[0].focus).toHaveBeenCalled();

    });

});

A와 함께directive그리고.link다음과 같은 기능이 있습니다.

(function () {

    'use strict';

    angular.module('auto-focus-module')
        .directive('autoFocusDirective', autoFocusDirective);

    function autoFocusDirective () {

        return {
            link: link
        };

        function link (scope, elem) {

            elem[0].focus();

        }

    }

})();

angular.element api - jQuery lite - 를 사용하고 triggerHandler() 메서드를 사용해야 합니다.

it('should have focus', function() {
    elm.triggerHandler('focus');
    expect(elm).toBeInFocus() //PSEUDO CODE - you will need to see how this can be tested
}

http://docs.angularjs.org/api/ng/function/angular.element

http://api.jquery.com/triggerhandler/

일부 테스트 포커스 지식의 잠재적 영역:

https://shanetomlinson.com/2014/test-element-focus-javascript

또한 단위 테스트와 관련하여 - 본체에 요소를 추가할 필요가 없고, 그렇지 않아도 테스트가 가능합니다.

언급URL : https://stackoverflow.com/questions/22330098/how-do-i-check-if-my-element-has-been-focussed-in-a-unit-test

반응형