茉莉花测试模拟Tab键按下并检测新聚焦的元素

And*_*rew 5 html javascript jasmine

我有一个茉莉花测试,其中有2个输入字段。我将重点放在第一个输入上,然后在“ tab”键上模拟击键,并期望焦点在第二个输入上。不幸的是,这种情况并非如此。焦点从第一个开始没有改变,我的测试失败了。如何解决此问题,以使失败的测试通过?

我要测试的小提琴:http : //jsfiddle.net/G2Qz3/1/

Jasmine测试失败的小提琴:http//jsfiddle.net/mFUhK/4/

HTML:

<input id="first"></input>
<input id="second"></input>
Run Code Online (Sandbox Code Playgroud)

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');   
    });
});
Run Code Online (Sandbox Code Playgroud)

Izh*_*aki 5

无法做到这一点。请参阅此SO问题,该问题基于本教程,内容为:

请注意,手动触发事件不会生成与该事件关联的默认操作。例如,手动触发焦点事件不会导致元素获得焦点(您必须为此使用其focus方法),手动触发提交事件不会提交表单(使用Submit方法),手动触发关键事件不会不会导致该字母出现在焦点文本输入中,并且手动触发链接上的click事件不会导致链接被激活,等等。对于UI事件,出于安全原因,这很重要,因为它会阻止脚本模拟与浏览器本身交互的用户操作。