Search code examples
iosxcode-ui-testing

IOS UI Test case for toggle button inside text field


I am using the XCTest framework which is the default testing framework for UI Testing in IOS. I am writing a test case to check whether the text inside the text field is visible or hidden by clicking the hide show toggle button.

IOS Toggle button inside text field

The problem is that the toggle button is inside the text field and I am unable to access the toggle button. On recording, it considers the tap on toggle button as tap on text field and generates code as follows :

let secureTextField = element3.children(matching: .other).element(boundBy: 1).children(matching: .secureTextField).element
        secureTextField.tap()

Solution

  • You may need to do 2 things:

    1. Set the toggle as an accessibility element
    2. Give the toggle an accessibility identifier

    Both may not be necessary depending on your current setup.

    // app code
    let toggleButton: UIButton!
    toggleButton.isAccessibilityElement = true
    toggleButton.accessibilityIdentifier = "showHideToggle"
    

    This should allow XCTest to see the toggle and give you an easy mechanism to find it in your test code:

    // test code
    let app = XCUIApplication()
    let toggle = app.buttons["showHideToggle"]
    toggle.tap()