Setting radio button with Casperjs

╄→尐↘猪︶ㄣ 提交于 2019-12-23 18:41:16

问题


I'm trying without success to set the value of a radio button with CasperJS.

Can somebody explain to me why the assertEval is failing on this test?

    this.test.assertExist('input[name=main][value=yes]');

    casper.thenEvaluate(function(term) {
        document.querySelector('input[name=main][value=yes]').setAttribute('checked', true);
    });

    this.test.assertEval(function() {
        return document.querySelector('input[name=main][value=yes]').getAttribute('checked') == "true";
    }, 'Main was set to true');

回答1:


To understand why this assert is failing, we need to understand that each call to casper.then defines a new navigation step, and casper.run executes each step in the order that they're defined. So the code within your casper.then block is an async callback.

If you annotate your code like this:

    this.test.assertExists('input[name=main][value=yes]');

    casper.then(function() {
        this.echo('Select the radio button');
        this.evaluate(function() {
            document.querySelector('input[name=main][value=yes]').setAttribute('checked', true);
        }
    });

    this.echo('Assert that the radio button is selected');
    this.test.assertEval(function() {
        return document.querySelector('input[name=main][value=yes]').getAttribute('checked') == "true";
    }, 'Main was set to true');

You will notice that "Assert that the radio button is selected" gets printed before "Select the radio button". So there's your problem!

The Solution:

You may not need to use then if you're not performing any navigation steps. In that case, you can simply use evaluate instead of thenEvaluate. Or if you really need to use then, just put assertEval into the same casper.then block:

    this.test.assertExists('input[name=main][value=yes]');

    casper.then(function() {
        this.evaluate(function(term) {
            document.querySelector('input[name=main][value=yes]').setAttribute('checked', true);
        });
        this.test.assertEval(function() {
            return document.querySelector('input[name=main][value=yes]').getAttribute('checked') == "true";
        }, 'Main was set to true');
    });


来源:https://stackoverflow.com/questions/15967945/setting-radio-button-with-casperjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!