Friday, August 17, 2018

getElements method in nightwatch js


Nightwatch js does not have getElements methods to locate multiple elements but it has provided with WebDriver methods specified in the WebDriver Specification. These methods can be used to create your own getElements method. Below is one such implementation

To achieve this, we have to set selector strategy which can be done by examining locator string. Below is my implementation

    /**
     * It will return the slector strategy for the given selector string
     */
    getSelectorStrategy: function (locator) {
        if (locator.startsWith("//")) {
            return "xpath";
        } else {
            return "css selector";
        }
    } 

Using above method, elements method can be implemented as below
const {client} = require('nightwatch-cucumber');

 /**
   * This will retrun array of elements for the given selectors
   */
   getElements: function (locator, callback) {
       var selectorStrategy = this.getSelectorStrategy(locator);
       return client.elements(selectorStrategy, locator, function (result) {
           callback(result.value)
       });
    }