-
NightwatchJS Command to Repeat a Keystroke
Here’s a simple custom command that lets you repeat a specific key (single or combo) N number of times.
In the Drupal world you want to place this in your “Commands” directory (as defined in DRUPAL_NIGHTWATCH_SEARCH_DIRECTORY in web/core/.env).
You’d want to change “sitename” to be your site’s name (so it feels namespaced).
/tests/Nightwatch/Commands/sitenameRepeatKeystroke.js
123456789101112131415161718192021222324252627282930313233/*** Repeats a keystroke (can be multiple keys) a specific number of times.** @param {array} keys* Array of keys to send.* Example 1: [browser.Keys.TAB]* Example 2: [browser.Keys.SHIFT, browser.Keys.TAB, browser.Keys.NULL]);* (it's important to terminate modifier keys with NULL)* @param {integer} times* Number of times to repeat the key send.* @param {integer} pauseBetween* Number of milliseconds to pause between each key send (100 ms default).* @param {function} callback* A callback which will be called.* @return {object}* The 'browser' object.*/exports.command = function myCommand(keys, times, pauseBetween = 100, callback) {const self = this;for (let i = 0; i < times; i++) {this.keys(keys);if (pauseBetween) {this.pause(pauseBetween);}}if (typeof callback === 'function') {callback.call(self);}return this;};Using this in /tests/Nightwatch/Tests/misc.js with a 1000ms pause between each keystroke:
12345678910111213/* eslint-disable no-unused-expressions */module.exports = {'@tags': ['mysite', 'learn-page', 'accessibility'],'When I hit shift-tab 9 times on the Learn page my logo becomes the active element': browser => {browser.drupalRelativeURL('/learn');browser.sitenameRepeatKeystroke([browser.Keys.SHIFT, browser.Keys.TAB, browser.Keys.NULL],9,1000,);},};