3
votes

I am trying to write a do-try-catch in swift for my iOS UI test which uses XCUI testing. I am reading the error-handling section: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42-ID508 but am unsure of which error should be thrown when an element is not found.

func tapElement(string:String) throws {

    do{
        waitFor(app.staticTexts[string], 5)
        try app.staticTexts[string].tap()
    }
    catch {
        NSLog("Element was not found: \(string)")
        //how can i check specifically that the element was not found?
    }


}

....

func waitFor(element:XCUIElement, seconds waitSeconds:Double) {
    NSLog("Waiting for element: \(element)")
    let exists = NSPredicate(format: "exists == 1")
    expectationForPredicate(exists, evaluatedWithObject: element, handler: nil)
    waitForExpectationsWithTimeout(waitSeconds, handler: nil)
}

any help greatly appreciated!!

2

2 Answers

2
votes

You should use element.exists AND element.isHittable

element.exists checks whether the element is an element of the UIApplication/ScrollView/..

element.isHittable determines if a hit point can be computed for the element.

If you don't check for both, than element.tap() throws the following error, for example, if the element is under the keyboard:

Failed: Failed to scroll to visible (by AX action) TextField,...

Example code:

let textField = elementsQuery.textFields.allElementsBoundByIndex[i]

if textField.exists && textField.isHittable {
    textField.tap()
} else {
     // text field is not hittable or doesn't exist!
     XCTFail()
 }
1
votes

You shouldn't need to try-catch finding elements in UI Testing. Ask the framework if the element exists() before trying to tap() it.

let app = XCUIApplication()
let element = app.staticTexts["item"]
if element.exists {
    element.tap()
} else {
    NSLog("Element does not exist")
}

Check out my blog post on getting started with UI Testing for more specific examples, like tapping an button.