3

In one of my view controllers, I have code like:

class ViewController: UIViewController {
    @IBOutlet weak var _tableView: UITableView!

    private lazy var searchBar: UISearchBar = {
        let searchBar:UISearchBar = UISearchBar()
        searchBar.isAccessibilityElement = true
        searchBar.accessibilityLabel = "SearchField"
        searchBar.placeholder = "Search..."
        searchBar.sizeToFit()
        searchBar.isTranslucent = false
        searchBar.autocapitalizationType = .none
        searchBar.returnKeyType = .done
        searchBar.delegate = self

        return searchBar
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        isAccessibilityElement = true
        accessibilityLabel = "ViewController"

        _tableView.isAccessibilityElement = true
        _tableView.accessibilityLabel = "ItemList"
        _tableView.tableHeaderView = searchBar
    }
}

Now whenever I try to record UI test and select the searchBar, I get the following error:

Timestamped Event Matching Error: Failed to find matching element

I tried debugging to get the searchBar and following code, but it didn't match any element and assertion fails.

    let searchField = app.tables["ItemList"].otherElements.element(boundBy: 0).otherElements["SearchField"]
    XCTAssertTrue(searchField.exists)

Can you please show me what I did wrong? How can I access and test the searchBar? Thanks in advance.

x4h1d
  • 6,042
  • 1
  • 31
  • 46

2 Answers2

2

You can use the Debug View Hierarchy or the XCode open developer tool Accesibility Inspector from bottom to top looking for the view that isn't accessibility enabled.

BuguiBu
  • 1,507
  • 1
  • 13
  • 18
  • 2
    That view was added from code, so **Debug View Hierarchy** is not an option is this case. But the good news is, I found the **SearchField** using Accesibility Inspector. And it is in tableView `otherElements`, not in `element(boundBy: 0).otherElementes`. Thanks. – x4h1d Nov 20 '19 at 14:03
  • I didn't know that code generated views doesn't appears, tricky one. – BuguiBu Nov 20 '19 at 17:27
  • My bad. Views from code does appear at debugging view hierarchy. I was just impatient to find out from the mess of layers. + 1 for the comment, for which I searched again. – x4h1d Nov 21 '19 at 14:40
  • No prob, at least you tried Accessibility Inspector that worth the try – BuguiBu Nov 22 '19 at 08:20
1
  1. The built-in recorder is bad, you should write test code yourself.

  2. Find the element in VoiceOver hierarchy with print(app.debugDescription)

  3. Your XCUIElementQuery is a little bit longer than it should be. Try to shorten it like app.otherElements["SearchField"]

Roman Zakharov
  • 2,185
  • 8
  • 19