Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting radio button with Casperjs

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');
like image 814
z1naOK9nu8iY5A Avatar asked Jan 31 '26 04:01

z1naOK9nu8iY5A


1 Answers

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');
    });
like image 136
sirentian Avatar answered Feb 02 '26 05:02

sirentian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!