Search code examples
pythonangularseleniumselenium-webdrivertry-catch

How to identify if Angular toggle-switch toggle is clicked?


I am trying to define if Angular's toggle-switch is clicked or not using Selenium and Python tools. When open a new form my input id has class ng-untouched ng-pristine ng-valid.

After clicked, it changes to ng-valid ng-dirty ng-touched. But after a third click nothing changes. After I click it and save the form, the class stays always ng-valid ng-dirty ng-touched and remains the same after any change (even after disabling toggle and saving). This is not a bug because changes are saved on server side.

Which CSS property should I look at to define what is changed? Here is html code sample:

<div _ngcontent-c26="" class="form-group">
    <label _ngcontent-c26="" for="checked">Checked</label>
    <div _ngcontent-c26="" class="toggle-switch">
        <input _ngcontent-c26="" id="opened" name="checked" type="checkbox" class="ng-valid ng-dirty ng-touched">
            <label _ngcontent-c26="" for="checked"></label>
        </div>
        <span _ngcontent-c26="" class="form-control-helper"></span>
    </div>

Solution

  • After trying a few options and more research I found two solutions to test is a toggle/checkbox is checked. First, by using .is_selected() Selenium's method:

    driver.find_element_by_css_selector("input[type=checkbox]").is_selected()
    

    It returns True if a toggle is ON and False if it is OFF.

    Second, I looked closely and CSS settings and found out that when a toggle is ON, :checked is added to it. So, you can use a boolean expression for this locator. In Chrome's DevTools this attribute can be found in Properties tab, the name is checked. More details are here:

    The locator for checked toggle will look like:

    input[type=checkbox]:checked
    

    For unchecked:

    input[type=checkbox]
    

    Also, there is a third option which will work for many cases. For example, if a toggle changes its color, its property is also changed. So you can use:

    driver.find_element_by_css_selector("input[type=checkbox]").value_of_css_property("background-color") == "some color"
    

    For example, place "#fff" (white) if you expect this CSS property to be white.