nalexn / ViewInspector

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

Inspecting custom modifier doesn't see removed views #262

Closed noahsmartin closed 8 months ago

noahsmartin commented 9 months ago

I have a view like this:

struct TestView: View {
  var body: some View {
    Text("testing")
  }
}

and a modifier like this:

struct TestModifier: ViewModifier {
    func body(content: Self.Content) -> some View {
      Text("Hello world")
    }
}

I would expect that using the modifier: let v = TestView().modifier(TestModifier()) would result in a view that does not have a TestView so this test should pass:

XCTAssertThrowsError(try v.inspect().find(TestView.self))

However, the test fails, an error is not raised when finding TestView. Is this expected, or is there another way to assert that this modifier is removing the TestView?

nalexn commented 9 months ago

Hey - I would say this behavior is expected because the view's structure still contains the view, which ViewInspector sees and locates during the find. Similarly, if you do TestView().hidden(), the library would still succeed in finding this view. In this particular case, isHidden() check allows to verify the view is hidden.

If your intent is to test that your custom view modifier doesn't drop the content, you can write a find extension that locates viewModifierContent() (see these tests for reference, and this guide section).

If your intent is to test that your custom view will be hidden in runtime because that custom modifier is applied, there is currently no way to attest "absence" directly, but only indirect methods, such as locating the view and then verifying certain modifiers are or are not applied to this view or any of its parent views.