2

I'm testing a tableview the cell content in XCUItest. In my case, I don't know the order of the cell text, nor am I allowed to set an accessibility id for the text. How can I get the index of a cell given the text inside?

enter image description here

For instance, if I wanted to get the index of the cell containing text "Cell 2 Text" I would try something like this:

func testSample() {
    let app = XCUIApplication()
    let table = app.tables
    let cells = table.cells

    let indexOfCell2Text = cells.containing(.staticText, identifier: "Cell 2 Text").element.index(ofAccessibilityElement: "I dunno")
    print(indexOfCell2Text)
}

I feel like I'm close, but I'm unsure. Can anyone suggest a solution?

I apologize if this question has been asked before. I wasn't able to find anything specific about this.

References I visited beforehand: https://developer.apple.com/documentation/xctest/xcuielementquery/1500842-element

How can I verify existence of text inside a table view row given its index in an XCTest UI Test?

iOS UI Testing tap on first index of the table

leedex
  • 963
  • 8
  • 19

2 Answers2

1

The most reliable way really is to add the index into the accessibility identifier. But, you can't. Can you change the accessibility identifier of the cell instead of the text ?

Anyway, if you don't scroll your table view, you can handle it like that :

let idx = 0
for cell in table.cells.allElementsBoundByIndex {
    if cell.staticTexts["Text you are looking for"].exists {
        return idx
    }
    idx = idx + 1
}

Otherwise, the index you will use is related to cells which are displayed on the screen. So, after scrolling, the new first visible cell would become the cell at index 0 and would screw up your search.

cesarmarch
  • 617
  • 4
  • 13
0
for index in 0..<table.cells.count {
    if table.cells.element(boundBy: index).staticTexts["Your Text"].exists {
        return index
   }
}