damjandd
damjandd

Reputation: 707

UI Testing UITableView cell count

I'm trying to verify that a table view has been filled with a certain number of cells in my UI test. Here is my code:

XCUIApplication().tables.element.swipeUp()
let count = XCUIApplication().tables.element.children(matching: .cell).count
XCTAssert(count > 0)

The assert fails because the count is always 0, even though the swipe up scrolls the obviously successfully filled table view. I have also tried:

XCTAssert(app.tables.cells.count > 0)

with the same results. I even created an empty project with a table view with 3 static cells, in just one screen, to remove any other possible distractions for the UI test, and it still always returns 0. I'm testing on iOS 11 with Xcode 9.

Upvotes: 3

Views: 7444

Answers (2)

Ramis
Ramis

Reputation: 16539

XCUIApplication().tables.children(matching: .cell).count

Deletes all rows from the table view. Written using Xcode 11.1 and tested using SwiftUI.

func deleteAllCellsFromTable() {
    let app = XCUIApplication()
    let tablesQuery = app.tables

    app.navigationBars["Navigation Bar Title"].buttons["Edit"].tap()

    while app.tables.children(matching: .cell).count > 0 {
        let deleteButton = tablesQuery.children(matching: .cell).element(boundBy: 0).buttons["Delete "]
        deleteButton.tap()

        let deleteButton2 = tablesQuery.children(matching: .cell).element(boundBy: 0).buttons["trailing0"]
        deleteButton2.tap()
    }
}

Upvotes: 0

Chase Holland
Chase Holland

Reputation: 2258

Cells don't always register as cells, depending on how you have your accessibility configured. Double check that accessibility is actually seeing cells in Xcode menu -> Open Developer Tool -> Accessibility Inspector.

It's likely what accessibility is seeing is staticTexts instead of cells, depending on your layout code -- in that case, you should assert

XCTAssert(app.tables.staticTexts.count > 0)

If you want cells, configure your cells like so in tableView:cellForItemAtIndexPath:

cell.isAccessibilityElement = true
cell.accessibilityLabel = cell.titleLabel.text // (for example)
cell.accessibilityIdentifier = "MyCellId" // (or whatever you want XCUITest to identify it as)

This will mark the cell as the root accessible item, rather than each of the cell's subviews being discrete elements.

Upvotes: 13

Related Questions