<select> 使用CasperJS/PhantomJS从表单字段中选择多个选项的正确方法



我在一个表单上存在两个多选择字段的网页的自动化测试。左边的包含国家名称列表,右边的包含您选择的国家名称。国家可以在一个名单上存在,但不能在另一个名单上存在。当你点击一个国家时,它会移动到另一个列表(你懂的)。当表单被提交时,POST中的值看起来像这样(来自chrome检查):

<>之前数据[运动][unselected_country_codes]:数据[运动][unselected_country_codes][]:房颤数据[运动][unselected_country_codes] []: AX数据[运动][unselected_country_codes] []:数据[运动][unselected_country_codes] []: DZ数据[运动][unselected_country_codes] []:数据[运动][unselected_country_codes][]:广告数据[运动][unselected_country_codes][]:奥数据[运动][unselected_country_codes] []: AI数据[运动][unselected_country_codes] []: AG)数据[运动][unselected_country_codes][]:基于"增大化现实"技术…(所有未选择的国家均在此列表中)数据[运动][country_code]:数据[运动][country_code][]:我们数据[运动][country_code] []: AQ数据[运动][country_code][]:双相障碍…(这部分包含我们挑选的)之前

,下面是你想要包含的国家列表的HTML:

<select name="data[Campaign][country_codes][]" multiple="multiple" id="CampaignCountryCodes" data-quicklist-ref="CampaignCountryCodes_quick" data-alter-ref="CampaignCountryCodes_alter">
<option value="US" selected="selected">United States</option>
<option value="AQ" selected="selected">Antarctica</option>
<option value="BD" selected="selected">Bangladesh</option>
</select>

我不明白的是,我该如何在测试时设置这些表单值?我真的不明白<select>属性的形式是通过一个数组值或什么?我希望能够提交表格,并有一个国家的名单,是在,和一个名单,是关闭。

下面是一个例子,我做了什么来设置其他值的形式,正确地工作。我真的不知道如何为一个倍数做这个,这是被问到的问题。

这个例子是一个非常好的文本区域。

casper.waitForSelector(x('//*[@id="some text area"]'),
   function success() {
        test.assertExists(x('//*[@id="some text area"]'));
        this.fill('form#campaign_form', { 
            'data[Campaign][some_field]': 'include',
            'data[Campaign][the_field]': myvar + "n"
        }, true); 
   },
   function fail() { ... }
);

您可以将选项从一个选项移动到另一个选项:

casper.evaluate(function(){
    var values = ["US", "CA"];
    var src = document.querySelector('[name="data[Campaign][unselected_country_codes][]"]');
    var dest = document.querySelector('[name="data[Campaign][country_codes][]"]');
    values.forEach(function(val){
        dest.appendChild(src.querySelector('[value="'+ val +'"]'));
    });
});

之后,您可能仍然需要选择它们。仅仅因为选项出现在选择框中并不意味着当您提交它们所在的表单时它们被发送到服务器。您需要选择以下值:

casper.evaluate(function(){
    var values = ["US", "CA"];
    var src = document.querySelector('[name="data[Campaign][unselected_country_codes][]"]');
    var dest = document.querySelector('[name="data[Campaign][country_codes][]"]');
    values.forEach(function(val){
        dest.appendChild(src.querySelector('[value="'+ val +'"]'));
    });
    // select intended values
    [].forEach.call(dest.options, function(opt){
        if (values.indexOf(opt.value) !== -1) {
            opt.selected = true;
        }
    });
    // trigger change event to run some page JavaScript
    var evt = document.createEvent("UIEvents");
    evt.initUIEvent("change", true, true);
    dest.dispatchEvent(evt);
});

我怀疑所有这些都是不必要的,因为你应该能够选择必要的选项,正如在CasperJS/Javascript选择多个选项中看到的,它们应该出现在目标选择框中。

最新更新