Jasmine test simulate tab keydown and detect newly focused element

拈花ヽ惹草 提交于 2020-01-14 10:02:28

问题


I have a jasmine test where I have 2 input fields. I am focusing on an first input, then simulating a keydown on the 'tab' key, and expecting focus to be on the second input. Unfortunately this is not the case. The focus does not change from the first and my test is failing. How can this be fixed so the failing test passes?

Fiddle of what I'm trying to test: http://jsfiddle.net/G2Qz3/1/

Fiddle of the failing Jasmine test: http://jsfiddle.net/mFUhK/4/

HTML:

<input id="first"></input>
<input id="second"></input>

JavaScript:

function simulateTab() {
    var TAB_KEY = 9;
    var keyboardEvent = document.createEvent("KeyboardEvent");
    var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
    keyboardEvent[initMethod]("keydown", true, true, window, 0, 0, 0, 0, 0, TAB_KEY);
    document.dispatchEvent(keyboardEvent);
}

describe('input tabbing test', function() {    
    beforeEach(function() {
        document.getElementById('first').focus();
    });

    //this passes
    it('input with id "first" should be focussed', function() {
        expect(document.activeElement.getAttribute('id')).toBe('first');
    });

    //this fails
    it('input with id "second" should be focussed after tabbing', function() {
        simulateTab(); 
        expect(document.activeElement.getAttribute('id')).toBe('second');   
    });
});

回答1:


This cannot be done. See this SO question, which is based on this tutorial which says:

Note that manually firing an event does not generate the default action associated with that event. For example, manually firing a focus event does not cause the element to receive focus (you must use its focus method for that), manually firing a submit event does not submit a form (use the submit method), manually firing a key event does not cause that letter to appear in a focused text input, and manually firing a click event on a link does not cause the link to be activated, etc. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself.



来源:https://stackoverflow.com/questions/25032300/jasmine-test-simulate-tab-keydown-and-detect-newly-focused-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!