3
votes

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.

1
I think this is a bug in the UITest framework. I tried differen approaces but even when you record the test it gives you the same error. Maybe file a radar at Apple?joern
Please make sure that your simulators hardware keyboard connection is desabled. You can find it on Hardware --> Keyboard --> Connect Hardware keyboard is disabled.Mahmud Riad
Thanks for the responses. I am leaning toward it being a bug as well. I did try with the hardware keyboard disconnected. When that is disconnected I can get the app.keys["D"].tap() function to work (although you have to start with an uppercase character and then use lowercase or else it won't find the keys.)drew2dev
Okay, I think the issue is searchBar.isAccessibilityElement = true This is modifying the accessibility type to .other instead of .searchField. Removing that line seems to fix the issue.drew2dev
Hello from 2019, this is still an issue. Setting the isAccessibilityElement to false helps.Steffen Andersen

1 Answers

1
votes

Step 1: Disable the hardware keyboard. You can find it on

Hardware --> Keyboard --> Connect Hardware keyboard [Disable this option]

Step 2:

 func testEnterTextInSearchBar() {        
 let app = XCUIApplication()

 // use one of below two  code
 let searchBarElement = app.otherElements["search-bar"].tap().firstMatch
 //let searchBarElement = app.searchFields["search-bar"].tap().firstMatch


 searchBarElement.tap()
 searchBarElement.typeText("test")

}

Please let me know the result.