我正在尝试为网站创建一个测试用例,其中包含一个包含3个链式选择的表单。 加载网页时默认填充第一个选择。如果选择了第一个选择中的任何选项,则 第二个选择是通过ajax调用填充的。以同样的方式,当选择第二个选项时,所以 第三个选择是通过ajax调用填充的。最后,当在第三个选择上选择一个选项时,将填充一个html表 我需要验证的信息。
三个互连的选择具有此结构
<select id="s1" name="s1">
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
</select>
<select id="s2" name="s2"></select>
<select id="s3" name="s3"></select>
我确信该网站使用Jquery来进行ajax调用。 有人用或知道用casperJs创建这种情况的干净方法吗?
答案 0 :(得分:8)
我是这样做的。因为Web上下文包含jQuery,我们可以使用它来触发事件,重要的一步是我们必须在每次ajax调用之后等待并验证才能处理任何下一步。
//set select values
var optionFirstSelect = 125;
var optionSecondSelect = 6;
var optionThirdSelect = 47;
//create casper object
var casper = require('casper').create({
loadImages:false,
verbose: true,
logLevel: 'debug'
});
//open url
casper.start('http://thewebsite.com');
casper.then(function(){
//select option on first select
this.evaluate(function(valueOptionSelect){
$('select#s1').val(valueOptionSelect);
$('select#s1').trigger('change');
},optionFirstSelect);
//wait until the second select is populated
this.waitFor(function check() {
return this.evaluate(function() {
return document.querySelectorAll('select#s2 option').length > 1;
});
}, function then() {
//select option on second select
this.evaluate(function(valueOptionSelect){
$('select#s2').val(valueOptionSelect);
$('select#s2').trigger('change');
},optionSecondSelect);
//wait until the third select is populated
this.waitFor(function check() {
return this.evaluate(function() {
return document.querySelectorAll('select#s3 option').length > 1;
});
}, function then() {
//select option on third select
this.evaluate(function(valueOptionSelect){
$('select#s3').val(valueOptionSelect);
$('select#s3').trigger('change');
},optionThirdSelect);
//wait until table with info is populated after an option is seleted on third select.
this.waitFor(function check() {
return this.evaluate(function() {
return document.querySelectorAll('table#info tbody tr').length > 1;
});
}, function then() {
//Do verifications here ...
});
});
});
});
casper.run(function() {
//finish execution script
this.exit();
});
答案 1 :(得分:3)
执行此操作的最简单方法是在将值更改为需要选项后在第一个选择上触发'onchange'事件,然后在第二个选项上触发相同的事件:
//...
// the first select
casperjs.thenEvaluate(function() {
var sel1 = document.getElementById('s1');
sel1.value = 3;
var evt = document.createEvent('HTMLEvents');
evt.initEvent('change', true, false);
sel1.dispatchEvent(evt);
});
// the second select
casperjs.thenEvaluate(function() {
var sel2 = document.getElementById('s2');
sel2.value = 'someVal2'; // guess, you know needed value
var evt = document.createEvent('HTMLEvents');
evt.initEvent('change', true, false);
sel2.dispatchEvent(evt);
});
// the third select
casperjs.thenEvaluate(function() {
var sel3 = document.getElementById('s3');
sel3.value = 'someVal3'; // guess, you know needed value
var evt = document.createEvent('HTMLEvents');
evt.initEvent('change', true, false);
sel3.dispatchEvent(evt);
});
casperjs.then(function() {
// your verifications here
});