Making a custom group of defined chaining methods in js
Asked 07 September, 2021
Viewed 2.2K times
  • 52
Votes

The question is related to general js programming, but I'll use nightwatch.js as an example to elaborate my query.

NightWatch JS provides various chaining methods for its browser components, like: -

 browser
    .setValue('input[name='email']','[email protected]')
    .setValue('input[name='password']', '123456')
    .click('#submitButton')

But if I'm writing method to select an option from dropdown, it requires multiple steps, and if there are multiple dropdowns in a form, it gets really confusing, like: -

 browser
    .click(`#country`)
    .waitForElementVisible(`#india`)
    .click(`#india`)
    .click(`#state`)
    .waitForElementVisible(`#delhi`)
    .click(`#delhi`)

Is it possible to create a custom chaining method to group these already defined methods? For example something like:

/* custom method */
const dropdownSelector = (id, value) {
    return this
        .click(`${id}`).
        .waitForElementVisible(`${value}`)
        .click(`${value}`)
} 

/* So it can be used as a chaining method */
browser
    .dropdownSelector('country', 'india')
    .dropdownSelector('state', 'delhi')

Or is there any other way I can solve my problem of increasing reusability and readability of my code?

2 Answer