2

I'm currently using NSPredicate to wait for conditions on XCUITest elements, as follows:

class func waitForCondition(condition: String, element: XCUIElement) -> Bool {
    let predicate = NSPredicate(format: condition)
    let expectation = XCTNSPredicateExpectation(predicate: predicate, object: element)
    let result = XCTWaiter().wait(for: [expectation], timeout: 5)
    return result == .completed
}

It works for most attributes, like "exists == 1", "isSelected == 1", "isHittable == 1", etc. But what I want is a way to check for focus and there doesn't seem to be a condition that would validate that.

To be honest, I can't find a way to check for focus even in Xcode's autocomplete. I found the documentation for XCUIElementAttributes, an interface which is adopted by XCUIElement class: https://developer.apple.com/documentation/xctest/xcuielementattributes and it states the existence of the "hasFocus" Bool. But it really doesn't seem to exist outside of the documentation world.

I'm using Xcode 9.4.1, for the record.

arvere
  • 727
  • 1
  • 7
  • 21
  • wait(for: [expectation(for: NSPredicate(format: "hasKeyboardFocus == true"), evaluatedWith: yourField, handler: nil)], timeout: 3) – Leszek Szary Jun 06 '22 at 12:24

1 Answers1

0

You can write an extension for XCUIElement. Something like:

extension XCUIElement { 

    var hasFocus: Bool {
        return self.value(forKey: "hasKeyboardFocus") as? Bool ?? false
    }

}

This will return true/false. You can use it like this:

if element.hasFocus == false {
    element.tap()
}
Václav
  • 990
  • 1
  • 12
  • 28