I am setting the titleView of a navigationItem for a UIViewController to be a UISearchBar. This works fine in the app, but now I am trying to add some UITesting and when I search for the element via an XCUIElementQuery it returns XCUIElement.Type as .other instead of .searchField which is what I expect. Subsequently my test crashes when I attempt to enter text into the field using XCUIApplication().typeText("abcd"). Here is some sample code:
In the view controller:
override func viewDidLoad() {
let searchBar = UISearchBar()
searchBar.isAccessibilityElement = true
searchBar.accessibilityIdentifier = "search-bar"
searchBar.delegate = self.searchViewController
self.navigationItem.titleView = searchBar
}
In the UITest:
func testEnterTextInSearchBar() {
let app = XCUIApplication()
let searchBarElement = app.descendants(matching: .any).matching(identifier: "search-bar").firstMatch
searchBarElement.tap()
app.typeText("test")
}
CRASH!!! because it thinks the type is .other and not .searchField
The error is: "Neither element nor any descendant has keyboard focus. Element: Attributes: Other, 0x608000192f10, traits: 8589934592, identifier: 'search-bar'"
Also using app.keys["x"].tap() works fine as long as the software keyboard is enabled.
searchBar.isAccessibilityElement = true
This is modifying the accessibility type to .other instead of .searchField. Removing that line seems to fix the issue. – drew2dev