简体   繁体   English

Javascript将链接的函数包装在单个函数中

[英]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. 我正在使用intern进行一些javascript功能测试,并希望开始对测试代码进行一些抽象,以使其更具可重用性。 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? 如果是这样,在我的两个新函数.findByXPath(xpath)...如何调用.findByXPath(xpath)...等?

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. 等等。关键是返回obj以便可以链接它。

如果要执行链接,则函数必须返回要在其上执行操作的“对象”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM