nalexn / ViewInspector

Runtime introspection and unit testing of SwiftUI views
MIT License
2.16k stars 148 forks source link

Find fails when view has recursion inside of ForEach #285

Closed starke0o closed 8 months ago

starke0o commented 9 months ago

Description

When view contains it self inside of a ForEach then find(text:) does not find text and fails with .searchFailure. When i check manually the searched text is found (see testGoToText in sample)

Minimal sample to reproduce

View with recursion inside of ForEach:

struct TreeView: View {
    struct Item: Identifiable {
        var id: Int { name.hashValue }

        var name: String
        var childs: [Item] = []
    }

    var item: Item

    var body: some View {
        VStack {
            Text(item.name)

            ForEach(item.childs, id: \.name) {
                TreeView(item: $0)
            }
        }
    }
}

Test case with failing test testFindText

class ViewInspectorFindBugTest: XCTestCase {
    let sut = TreeView(
        item: TreeView.Item(
            name: "Root",
            childs: [
                TreeView.Item(
                    name: "A",
                    childs: [
                        TreeView.Item(name: "A.1"),
                        TreeView.Item(name: "A.2"),
                    ]
                ),
                TreeView.Item(
                    name: "B",
                    childs: [
                        TreeView.Item(name: "B.1"),
                        TreeView.Item(name: "B.2"),
                    ]
                )
            ]
        )
    )

    func testFindText() throws {
        XCTAssertNoThrow(try sut.inspect().find(text: "A.2"))
    }

    func testGoToText() throws {
        XCTAssertEqual(
            "A.2",
            try sut
                .inspect().vStack().forEach(1)
                .view(TreeView.self, 0).vStack().forEach(1)
                .view(TreeView.self, 1).vStack().text(0).string()
        )
    }
}

Snapshot of testview: Bildschirmfoto 2023-12-21 um 13 51 43

nalexn commented 9 months ago

Thanks for the report! The fix is pending release