Handling Asynchronous Operations in Nightwatch.js: Getting and Comparing License Numbers
This article explains how to retrieve a license count using Nightwatch.js, manage JavaScript's asynchronous callbacks, compare two retrieved values, and assert the expected increment, providing complete code examples and practical tips for reliable UI automation testing.
In automated UI testing with Nightwatch.js, it is often necessary to obtain a value from a command or function and use it in subsequent steps; JavaScript requires a specific pattern for handling such asynchronous operations.
The getLicenseNum method demonstrates how to wait for a license element, retrieve all matching elements, and return the count via a callback:
getLicenseNum: function (cb) {
const license = 'ul > li.license-id.ng-binding';
this.waitForElementVisible(license, 5000);
this.api.elements('css selector', license, function (result) {
cb(result.value.length);
return this;
});
}To compare the license numbers obtained at two different moments, the test stores each count in separate variables and then asserts that the difference equals the expected increment:
'JavaScrpit asynchronous operation': function(client) {
const license = client.page.license();
let num1, num2;
license.getLicenseNum(function(num) {
num1 = num;
});
license.getLicenseNum(function(num) {
num2 = num;
});
client.perform(function() {
client.assert.equal(num2 - num1, 1, 'license number increase 1');
});
}Related articles discuss handling element position changes during automation and simulating keyboard actions in Nightwatch.
Readers are invited to share further questions or ideas about automation testing, forward the article, leave comments, and join the "Software Testing QA" QQ group (25398297) for more discussion.
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.