nalexn / ViewInspector

Runtime introspection and unit testing of SwiftUI views
MIT License
2.21k stars 153 forks source link

Element inspection not working #346

Closed rishipandey closed 3 days ago

rishipandey commented 1 month ago

have created a sample view with a List in XCode 16:

struct TestListView: View {
    let items = ["Item 1", "Item 2", "Item 3"]

    var body: some View {
        List {
            ForEach(items, id: \.self) { item in
                Text(item)
            }
        }
    }
}

Now, I have created inspection tests:

final class TestListViewTests: XCTestCase {

    func testListItemCount() throws {
        let view = TestListView()

        let list = try view.inspect().list()
        let forEach = try list.forEach(0)

        XCTAssertEqual(forEach.count, 3)
    }

    func testListItemContents() throws {
        let view = TestListView()

        let list = try view.inspect().list()
        let forEach = try list.forEach(0)

        XCTAssertEqual(try forEach[0].text().string(), "Item 1")
        XCTAssertEqual(try forEach[1].text().string(), "Item 2")
        XCTAssertEqual(try forEach[2].text().string(), "Item 3")
    }
}

However, these tests throw the following error: failed: caught error: "list() found TestApp_SwiftUI.TestListView instead of List"

Tronicnotes commented 4 weeks ago

@rishipandey You can resolve this by adding .view(TestListView.self) after calling .inspect(). I'm unsure why this is now required.

So in your example, you would write let list = try view.inspect().view(TestListView.self).list()

nalexn commented 3 days ago

The above comment by @Tronicnotes is correct, I would just add that you can alternatively use find:

let list = try view.inspect().find(ViewType.List.self)