Using Nightwatch.js for Keyboard Actions and Key Combinations in Automated Web Testing
This article explains how to perform simple and combined keyboard actions such as Enter and Ctrl+A in Nightwatch.js automated tests, provides code examples for Google (or Baidu) searches, and lists all available key constants for reference.
In this article we share problems encountered and solutions when using Nightwatch.js for automated web testing, focusing on keyboard actions such as pressing the Enter key and using key combinations.
For a typical scenario we input a string into a text field, press Enter, and verify the search results, illustrated with Google search (or Baidu if Google is inaccessible). The example code is:
'search nightwatch and click ENTER key': function(client) {
client
.url('http://google.com')
.expect.element('body').to.be.present.before(1000);
client.setValue('input[type=text]', ['nightwatch', client.Keys.ENTER])
.pause(1000)
.assert.containsText('#main', 'Night Watch');
}If you cannot access Google, replace the URL with Baidu and adjust the element selectors accordingly.
To perform a key‑combination action, such as selecting all text with Ctrl+A, the code is:
client.setValue('input[type=text]', ['nightwatch', [client.Keys.CONTROL, 'a']])Other combination key operations follow the same pattern.
Below is the full list of key constants available in Nightwatch.js:
Keys:
{ NULL,
CANCEL,
HELP,
BACK_SPACE,
TAB,
CLEAR,
RETURN,
ENTER,
SHIFT,
CONTROL,
ALT,
PAUSE,
ESCAPE,
SPACE,
PAGEUP,
PAGEDOWN,
END,
HOME,
LEFT_ARROW,
UP_ARROW,
RIGHT_ARROW,
DOWN_ARROW,
ARROW_LEFT,
ARROW_UP,
ARROW_RIGHT,
ARROW_DOWN,
INSERT,
DELETE,
SEMICOLON,
EQUALS,
NUMPAD0,
NUMPAD1,
NUMPAD2,
NUMPAD3,
NUMPAD4,
NUMPAD5,
NUMPAD6,
NUMPAD7,
NUMPAD8,
NUMPAD9,
MULTIPLY,
ADD,
SEPARATOR,
SUBTRACT,
DECIMAL,
DIVIDE,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
COMMAND,
META
},Related reading: How to handle element position changes in automated testing?
DevOps Engineer
DevOps engineer, Pythonista and FOSS contributor. Created cpp-linter, commit-check, etc.; contributed to PyPA.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.