我终于回答了我自己的问题。问题是我正在使用 for(){} 循环来遍历我想要填写的不同字段。for(){} 循环正在执行每个命令,而无需等待给定的选择完成设置正确值(单击选择,输入值,按回车键)。我通过收集选择器和值来解决这个问题,将它们存储在一个函数中,并将每个完整的函数添加到一个队列中。然后我一次执行一个函数,在函数之前的“keys”命令的“then”回调中调用下一个函数(因此在继续选择的选择上按下回车键后调用下一个函数)。我使用迭代器来获取队列中的每个下一个函数。任何有兴趣的人都可以检查我的代码并评论任何问题以获取建议。谢谢!
webdriverio = require('webdriverio');
var tester = {};
var options = {
desiredCapabilities: {
browserName: 'chrome'
}
};
var params = {
//editing this out because info is private
};
//changing the fields because info is private
var fields = {
testField: 'John Smith',
testSelect: 'USA'
};
var execQueue = [];
var wrapFunction = function(fn, context, params) {
return function() {
fn.apply(context, params);
};
};
function fillFields(driver, fields){
driver.iter = 0;
driver.elements('select + .chosen-container').then(function(result){
console.log('how many selects', result.value.length);
tester.totalSelects = result.value.length;
});
//loop through all selects and inputs
for(property in fields){
var p = property;
//closure to preserve value of property
(function(p){
//if chosen input then choose from list
driver.isExisting('div.' + p + ' .chosen-results').then(function(result){
if(result === true){
driver.elements('div.' + p + ' select').then(function(result){
//loop through each select (expiration date has two selections in one container)
for(var i=0;i<result.value.length;i++){
var s = result.value[i].ELEMENT;
//closure
(function(s){
//find the name of each select
driver.elementIdAttribute(s,'name').then(function(result){
//find the chosen container after select
var container = 'select[name=' + result.value + '] + .chosen-container';
var selectName = result.value;
//find corresponding a.chosen-single
//this.debug()
//click on a.chosen-single to activate chosen drop
var qfunction = function(link, value){
console.log('#################in qu function ###########', value);
driver.click(link).then(function(){
this.keys([value, '\uE007']).then(function(){
driver.iter++;
execQueue[driver.iter]();
});//end keys.then
});//end click.then
}//end qfunction
execQueue.push(wrapFunction(qfunction, this, [container + ' a.chosen-single', fields[selectName]]));//end push
if(execQueue.length == tester.totalSelects - 1){
console.log('**********equal');
execQueue[driver.iter]();
}//end if equal
console.log('queue so far', execQueue.length);
});//end elementIdAttribute
})(s);//end closure
}//end for selects in container
});//end driver.elements
}else{
driver.addValue('input[name=' + p + ']', fields[p]);
}
})//end driver.isExisting
})(p);
}//end for each field
};//end fillFields
webdriverio
.remote(options)
.init()
.url('https://' + params.domain + '/' + params.clientId + '/?scope=' + params.scope + '&cart=' + params.cart + '&cfg=' + params.cfg + '&progress=' + params.progress + '&language=' + params.language + '¤cyId=' + params.currencyId + '&debug=nocache')
.then(function(result) {
fillFields(this, fields);
});