Set Keyboard Focus on an Element via WebdriverIO
Sometimes you need to set the focus on a specific element when running a test in WebdriverIO. For example, I recently wanted to test that pressing the 'spacebar' would toggle a setting. To do this, I needed to focus the element, then send a 'spacebar' keypress.
This is relatively easy to do in WebdriverIO via the browser.execute
command. What we'll do is run a small JavaScript snippet on the page, calling the built-in focus
function available on all DOM elements (note, the element must be 'focusable').
Here's what the code looks like:
it('should toggle checkbox when spacebar pressed and focused on label', function () {
const toggle = $('.someComplexToggleElement');
// run javascript to put keyboard focus on checkbox label
browser.execute(function (label) {
label.focus();
}, $('label'));
// press spacebar to toggle
browser.keys(['Space']);
expect(toggle.getAttribute('checked')).to.equal(true);
// toggle once more just to make sure
browser.keys(['Space']);
expect(toggle.getAttribute('checked')).to.equal(false);
});
You could even add this as a WebdriverIO command:
browser.addCommand('focus', function () {
browser.execute(function (domElement) {
domElement.focus();
}, this);
}, true);
And then run it via:
it('should use my custom command', function () {
$('label').focus();
})