Identifying SwiftUI list cells in XCUITest

In my macOS app I have a SwiftUI list that starts like this:

      List(selection: $selection) {
        HStack {
          Label("Staging", systemImage: "arrow.up.square")
          Spacer()
          WorkspaceStatusBadge(unstagedCount: model.statusCounts.unstaged,
                               stagedCount: model.statusCounts.staged)
        }

(where WorkspaceStatusBadge is a custom view that just contains a Text)

I'm trying to set the accessibility ID of that first cell so I can find it in XCUITest. If I apply the accessibilityIdentifier() modifier to the HStack, it instead sets the ID of the two static text elements inside it, and the cell still has no ID.

I could find the cell based on the ID of the child staticText, but I have some other cases where this doesn't work as well.

If I use .accessibilityElement() on the HStack, then XCUI sees a cell containing a Group element with the ID. This might be workable, but it's certainly not ideal.

So how do I set the ID of the cell itself?

@Uncommon

Create a container view for the list row, as an example we can call it DetailView. and use .accessibilityElement(children: .combine) to make a new accessibility element (DetailView) to separately track focus for the container HStack

   List(selection: $selection) {
            DetailView()
            .accessibilityElement(children: .combine)
            .accessibilityIdentifier("TestIdentifier")
        }

You could also use the Accessibility Inspector to audit your view hierarchy.

@Uncommon Thanks for providing that but's not a focused sample and would require me to fully understand what's going on in your project. Let's us this focused example instead:

struct DetailView: View {
    var body: some View {
        HStack {
            Label("Staging", systemImage: "arrow.up.square")
            Spacer()
            WorkspaceStatusBadge(count: 1)
        }
    }
}
struct ContentView: View {
    @State private var selection: String? = nil
    
    var body: some View {
        List(selection: $selection) {
            DetailView()
            .accessibilityElement(children: .combine)
            .accessibilityIdentifier("StagingCell")
        }
        .accessibilityIdentifier("List")
    }
}

struct WorkspaceStatusBadge: View {
    let count: Int
    
    var body: some View {
        Text("sample: \(count)")
    }
}

Here's the test,


    func testCellExists() throws {
        let app = XCUIApplication()
        app.launch()
        let list = app.collectionViews["List"]

        XCTAssertEqual(list.cells.count, 1)
        
        let cell = list.cells.element(boundBy: 0)
        XCTAssertTrue(cell.exists)
        
        let testLabel = cell.staticTexts["StagingCell"].label
        XCTAssertEqual(testLabel, "Staging, sample: 1")
    }

Here we're able to test for the existence of StagingCell.

Identifying SwiftUI list cells in XCUITest
 
 
Q