Search code examples
swiftxcodexcode-ui-testingxctestcase

XCUITest - Failed to find matching element


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.


Solution

  • 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.