nalexn / ViewInspector

Runtime introspection and unit testing of SwiftUI views
MIT License
2.09k stars 145 forks source link

Interface buttons by ID #296

Closed levyanjos closed 4 months ago

levyanjos commented 4 months ago

I've been trying to test a class with a lot of buttons and some of them don't have any label but image. I tried a lot triggering those buttons actions by ID with try? view.inspect().find(viewWithId: "testID").callOnTapGesture() but it doesn't worked at all.

At last, i was able to achieve this using

try? view.inspect().find(ViewType.Button.self) {
     if let id = try? $0.id() as? String {
         return id == "testID"
     } else {
         return false
     }
}.tap()

Wouldn't be better to have an interface to access this like view.inspect().find(buttonWithId: "testID").tap()? I think this is a pretty common case, not just me might have seen this issue.

nalexn commented 4 months ago

Hey, you can add custom find functions as discussed in this section of the guide. Here you go:

extension InspectableView {
    func find(buttonWithId id: AnyHashable) throws -> InspectableView<ViewType.Button> {
        return try find(ViewType.Button.self, where: {
            try $0.id() == id
        })
    }
}

The usage: try view.inspect().find(buttonWithId: "testID").tap()

LMK if this doesn't solve the issue for you - feel free to reopen