11

I am writing a unit test to test the tab order on my webpage and I could not find a way to simulate the user's keying down of the TAB key to focus on the next focusable element, though this seems to be an easy task.

jQuery is allowed while pure javascript solution is preferred. Any kind of help is appreciated.

// TODO
function triggerTab () {


}

$("#btn-save").focus();
triggerTab();

// Expect the focus is on the cancel button now.
console.log(document.activeElement.id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p> some text </p> 
<button id="btn-save"> save </button>
<button id="btn-cancel> cancel </button>

P.S. It is no acceptable to call focus() on the next focusable element, even if you can write code to figure out the next focusable element. So this path is NOT what I want:

function getAllFocusables () {
    ...
}

var focusables = getAllFocusables(),
    index = focusables.indexOf(document.activeElement);

$(focusables[index+1]).focus();
Jason Lee
  • 357
  • 2
  • 10
  • No there isn't a way to trigger the tab key, but there is a way to find the next focusable element in the DOM, and focusing it. Maybe whatever you're using to unit test this, has a way to trigger keys, I don't know, I never unit test simple event handlers ? – adeneo Nov 06 '16 at 21:31
  • 2
    Why do you NOT want to use the simpler method of focusing what you want directly. – VLAZ Nov 06 '16 at 21:32
  • 1
    @vlaz Because this is for the unit test of a module in my project, the module has js code to manage the tab order using the same idea as what I put at the end of the question. I think it is silly to use the same module's code to test itself. This is why I want to test it in this way, set up a markup, programmatically trigger the tabs and check if the tab order is as expected. – Jason Lee Nov 06 '16 at 21:42
  • This isn't a duplicate. The referenced question asks for why when the current one asks for how we can bypass this restriction. – Adam Dec 01 '16 at 07:51

1 Answers1

9

You can not simulate a tab key from a standard browser using Javascript.

If you are doing your unit test using a headless browser, like phantomjs for instance, you can emulate the tab key

var webPage = require('webpage');
var page = webPage.create();

page.sendEvent('keypress', page.event.key.Tab);
Adam
  • 17,838
  • 32
  • 54
  • This is wrong. You can simulate a tab key press because .focus() exists. By keeping track of each tabbable DOM element and focusing the next one in the list. Not an acceptable way to simulate it for unit tests but it works. – user3044394 Aug 28 '23 at 16:29
  • @user3044394 The question clearly states the using `focus()` is not an acceptable solution. – Adam Sep 01 '23 at 09:23