Jasmine测试模拟选项卡keydown并检测新聚焦的元素 [英] Jasmine test simulate tab keydown and detect newly focused element

查看:144
本文介绍了Jasmine测试模拟选项卡keydown并检测新聚焦的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个茉莉花测试,我有2个输入字段。我专注于第一个输入,然后在'tab'键上模拟keydown,并期望焦点在第二个输入上。不幸的是,这种情况并非如此。焦点不会从第一次改变,我的测试失败。如何解决这个失败的测试?

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?

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

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

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

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

HTML:

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

JavaScript:

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');   
    });
});


推荐答案

这是无法做到的。请参阅此SO问题,该问题基于本教程说:

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


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

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.

这篇关于Jasmine测试模拟选项卡keydown并检测新聚焦的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆