Select first cell in collection view from UITest
Asked Answered
M

1

10

Is there a way to select or trigger didSelect from a UITest on the first cell if it exists in a collection view?

When recording it uses static text from the selected cell. If the cell is populated from the network with dynamic content and with the collection view to possibly contain no cells, this test will break.

Mujik answered 29/12, 2015 at 17:30 Comment(0)
F
26

You can select the first cell in a collection view with:

let app = XCUIApplication()
app.launch()

let firstChild = app.collectionViews.childrenMatchingType(.Any).elementBoundByIndex(0)
if firstChild.exists {
    firstChild.tap()
}

Swift 3

let firstChild = app.collectionViews.children(matching:.any).element(boundBy: 0)
if firstChild.exists {
     firstChild.tap()
}

On a more theoretical note, your test suite should use deterministic data. You should always know exactly how many cells, and what they contain, will be returned from the service. You can accomplish this by using a seeded development server or mocking out network requests when running your test suite.

Freckly answered 30/12, 2015 at 13:38 Comment(2)
Thanks Joe. Regarding the deterministic data, I agree, but the test is for screenshots and it needs real data from the server. I ended up setting the accessibilityIdentifier of each cell based on cell type and index path and checking if it exists before accessing it.Mujik
"You should always know exactly how many cells, and what they contain, will be returned from the service." Took me a bit to figure out that the count of cells is just whatever is drawn, and will vary by screen size. So when I wanted the first cell in section 3, I had to know how many were in sections 1 and 2, and ensure that section 3 would actually be visible on the test device, and not just that it existed in my collection view and my data.Discontinuity

© 2022 - 2024 — McMap. All rights reserved.