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 text = try view.inspect().vStack().text(2).string()
XCTAssertEqual(text, "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
.
Check out the detailed list. There is currently almost full support for SwiftUI 1.0 API, the 2.0 support is under active development.
You are welcomed to contribute! Use po Inspector.print(view) as AnyObject
in lldb for printing the inner view structure - this is the tool that would help you dig super fast!
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.
Swift Package Manager
- 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
Carthage
github "nalexn/ViewInspector"
CocoaPods
pod 'ViewInspector'
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.