Search code examples
javascriptchainingintern

Javascript wrapping chained functions in a single function


I am using intern for some javascript functional tests, and would like to start abstracting my test code out a little to make it a bit more reusable. Im not sure if this is even possible, but I am trying to achieve the following -

My original code has the following format -

this.remote.get(URL).setFindTimeout(5000).end()
.findByXpath(xpath).click().type('XXX').end().
.findByXpath(xpath).click().type('YYY').end()
.findByCSSSelector(css).click().doSelectBoxStuff().end() //and so on...

Where each line could possibly be the input of a different type of input field. I am trying to abstract out the functionality, when entering into these different input types, into their own functions, like this -

this.remote.get(URL).setFindTimeout(5000).end()
    .enterTextBox('XXX')
    .enterTextBox('YYY')
    .enterSelectBox('ZZZ')

function enterTextBox(val){
    //execute  .findByXpath(xpath).click().type(val).end()
}

function enterSelectBox(val){
    //execute  .findByCSSSelector(css).click().doSelectBoxStuff().end()
}

Is something like this possible? If so, what would call .findByXPath(xpath)... etc on within my two new functions?


Solution

  • You absolutely can. Just pass functions as arguments to functions. You can define methods for an object by changing its prototype. So to achieve the behavior you want, you'd write this:

    // Ideally, replace this.remote.get(URL) with a base instance of the object
    this.remote.get(URL).prototype.enterTextBox = function() {
        return this.findByXpath(xpath).click().type(val).end()
    }
    
    this.remote.get(URL).setFindTimeout(5000).end()
        .enterTextBox('XXX')
    

    etc. The key thing is to return the obj so it can be chained.