Cannot access SwiftUI Text in XCTestCase UI Test

Viewed 43

I am trying to add UI tests to a SwiftUI project.

I have a list, which contains views - those then contain a number of views.

I cannot seem to access the furthest most view in my UI test.

I thought I could add an accessibility identifier to each element but I cannot make my test pass still.

A very simple example;

ContentView

struct ListModel: Identifiable {
    let id: String
    let text: String
}

struct ContentView: View {
    
    private var state = (0..<50).map { ListModel(id: "\($0)", text: "Row \($0)") }
    
    var body: some View {
        List(state, id: \.id) { item in
            ContentViewRow(text: item.text)
                .accessibility(identifier: "FEED_ITEM")
        }
        .accessibility(identifier: "FEED")
    }
}

struct ContentViewRow: View {
    let text: String
    var body: some View {
        Text(text)
            .accessibility(identifier: "CONTENT_ROW_TEXT")
    }
}

Tests

class TestingSwiftUIUITests: XCTestCase {

    func testExample() throws {
        // UI tests must launch the application that they test.
        let app = XCUIApplication()
        app.launch()
        
        let feed = app.tables["FEED"]
        XCTAssert(feed.waitForExistence(timeout: 0.5))

        let row0 = feed.staticTexts["FEED_ITEM"].firstMatch
        XCTAssert(row0.waitForExistence(timeout: 0.5))
        
        let textView = row0.staticTexts["CONTENT_ROW_TEXT"].firstMatch
        XCTAssert(textView.waitForExistence(timeout: 0.5)) // <-- This fails.
    }
}

How can I access a view inside ContentViewRow - thank you.

1 Answers

identifier: "CONTENT_ROW_TEXT" seems to be overriden by identifier: "FEED_ITEM" Perhaps you can leave just "FEED_ITEM" and check for the label text if needed.

    let row0 = feed.staticTexts["FEED_ITEM"].firstMatch
    XCTAssert(row0.waitForExistence(timeout: 0.5))
    XCTAssert(row0.label == "Row 0")
Related