使用CasperJS从击倒下拉列表中获取选定值

时间:2022-12-03 07:49:38

I have a dropdown which was created using KnockoutJS. Now I am writing UI test and I want to fetch the selected item in the dropdown for my UI test (I am using CasperJS). The problem is that when I write > option[selected="selected"] next to the selector for the dropdown I get undefined. Note that I want to do this without changing the .js file, only the test. How would I do that?

我有一个使用KnockoutJS创建的下拉列表。现在我正在编写UI测试,我想在我的UI测试的下拉列表中获取所选项目(我正在使用CasperJS)。问题是,当我在下拉列表的选择器旁边写>选项[selected =“selected”]时,我得到了未定义。请注意,我想在不更改.js文件的情况下执行此操作,仅更改测试。我该怎么办?

1 个解决方案

#1


0  

CasperJS doesn't directly provide a function to get the selected value, but you can use normal DOM operations to get the data

CasperJS不直接提供获取所选值的函数,但您可以使用常规DOM操作来获取数据

var selector = "select"; // use proper selector
casper.then(function(){
    var selected = this.evaluate(function(selector){
        var s = document.querySelector(selector);
        var o = s.children[s.selectedIndex];
        return {value: o.value, text: o.innerHTML};
    }, selector);
    this.echo("result: " + JSON.stringify(selected, undefined, 4));
});

You may also need to wait for the select element to appear:

您可能还需要等待select元素出现:

casper.waitForSelector(selector + " > option")
    .then(function(){/* from above */});

#1


0  

CasperJS doesn't directly provide a function to get the selected value, but you can use normal DOM operations to get the data

CasperJS不直接提供获取所选值的函数,但您可以使用常规DOM操作来获取数据

var selector = "select"; // use proper selector
casper.then(function(){
    var selected = this.evaluate(function(selector){
        var s = document.querySelector(selector);
        var o = s.children[s.selectedIndex];
        return {value: o.value, text: o.innerHTML};
    }, selector);
    this.echo("result: " + JSON.stringify(selected, undefined, 4));
});

You may also need to wait for the select element to appear:

您可能还需要等待select元素出现:

casper.waitForSelector(selector + " > option")
    .then(function(){/* from above */});