iosswiftxctestxcuitest

In XCUITest, unable to tap() on Switch


I have a simple screen with three switches. I have added the accessibilityindetifier to the the switches and also confirmed that the switch is enabled, hittable,not Selected. But when I get no response when I try to tap() on the element. The steps passes without errors the switch state does not change.

 let daSwitch = app.switches["LocationSwitch"]
 daSwitch.tap()

I tried doubleTap() and put sleeps between taps as well. The accessibility inspector is able to identify the element as well.

Tap() is working on switches on other screens, but not on this particular screen. I am not sure what could prevent the tap from being recognized/executed.

Any suggestions what could be going on here?

enter image description here

Xcode Version: 14.3 (14E222b)


Solution

  • Check if the switch element is properly identified: Ensure that you are correctly identifying the switch element using its accessibility identifier or label. To debug this, you can print all the switch elements to the console and verify that you are targeting the right element:

    let allSwitches = XCUIApplication().switches
    print("All switches: \(allSwitches.debugDescription)")
    

    Use coordinate-based tap: In some cases, the tap() function might not work as expected. You can try using a coordinate-based tap on the switch element:

    let switchElement = XCUIApplication().switches["yourSwitchAccessibilityIdentifier"]
    let coordinate = switchElement.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))
    coordinate.tap()
    

    Wait for element to be hittable: It is also possible that the switch is not ready for interaction at the moment you are trying to tap it. Make sure the element is hittable before trying to tap:

    let switchElement = XCUIApplication().switches["yourSwitchAccessibilityIdentifier"]
    let isSwitchElementHittable = switchElement.waitForExistence(timeout: 10)
    if isSwitchElementHittable {
        switchElement.tap()
    } else {
        print("Switch element is not hittable.")
    }
    

    Let me know if this helps you