Search code examples
javascriptangularjsprotractore2e-testing

Checking a radio button in Protractor + AngularJS


I have a radio button on my html page and I'd like to test the value of the current selected option

        <div>
            <input type="radio" name="radio1" value="enabled" checked/>
            <label for="radio1">Yes</label>
        </div>
        <div>
            <input type="radio" name="radio1" value="disabled" />
            <label for="radio1">No</label>
        </div>
        <br />

I'm using this code on the page object I use to test

var radio = $("input[type='radio'][name='radio1']:checked").val();

Unfortunately I get

val() is undefined

How can I return "enabled" or "disabled" based on the current status of the radio button?


Solution

  • val() is a jQuery function which you do not inherently have access to unless you setup Protractor that way. Use getAttribute('value') instead, which returns a promise - see the getAttribute() reference

    So if you are using it in an assertion, you can let expect resolve the promise itself:

    var radio = $("input[type='radio']:checked")
    expect(radio.getAttribute('value')).toEqual('enabled');
    

    Or if you want to access the value and use it elsewhere, resolve the promise yourself:

    radio.getAttribute('value').then(function (val) {
        if(val === 'enabled') {
            // code
        }
    });