ViewInspector is a library for unit testing SwiftUI views.
It allows for traversing a view hierarchy at runtime providing direct access to the underlying View
structs.
SwiftUI views are a function of state. We can provide the input, but couldn't verify the output. Until now!
You can dig into the hierarchy and read the actual state values on any SwiftUI View:
func testVStackOfTexts() throws {
let view = VStack {
Text("1")
Text("2")
Text("3")
}
let values = try view.inspect().map { try $0.text().string() }
XCTAssertEqual(values, ["1", "2", "3"])
}
You can simulate user interaction by programmatically triggering system-controls callbacks:
let button = try view.inspect().hStack().button(1)
try button.tap()
let list = try view.inspect().list()
try list[5].view(RowItemView.self).callOnAppear()
It is possible to obtain a copy of your custom view with actual state and references from the hierarchy of any depth:
let sut = try view.inspect().tabView().navigationView()
.overlay().anyView().view(CustomView.self).actualView()
XCTAssertTrue(sut.viewModel.isUserLoggedIn)
The library can operate with all types of the View's state: @Binding
, @State
, @ObservedObject
and @EnvironmentObject
.
Pretty much all! Check out the detailed list.
The framework is still expanding, as there are hundreds of inspectable attributes in SwiftUI that are not included yet. Contributions are welcomed!
ViewInspector is using official Swift reflection API to dissect the view structures.
So this framework is production-friendly for the case if you accidentally (or intentionally) linked it with the build target.
- In Xcode select File ⭢ Swift Packages ⭢ Add Package Dependency...
- Copy-paste repository URL: https://github.com/nalexn/ViewInspector
- Hit Next two times, under Add to Target select your test target. There is no need to add it to the build target.
- Hit Finish
Please refer to the Inspection guide. You can also check out my other project that harnesses the ViewInspector for testing the entire UI.
Ping me on Twitter or just submit an issue or a pull request on Github.