SwiftUI Unit Testing
Alexey Naumov (via Peter Steinberger):
So I decided to build ViewInspector, a library that allows for inspecting the SwiftUI view hierarchy at runtime.
[…]
And as it turned out, there were many pitfalls waiting for me on the way:
- All types in reflection are erased to
Any
- Computed properties, such as
var body: some View
, are not available in reflection- Generic private structs and function types which are tricky to cast the value to
- Initializing a struct which all
init
methods are private- SwiftUI dependency injection through
Environment
- Property wrappers, such as
@State
, with an elusive storage for values- Significant variations of the hierarchy after a tiny tweak of the input. For example,
Text("Hi")
vsText(hiValue)
- Overall obscurity and lack of information about the private structures
In this piece, I want to share abnormal use cases and hacky tricks I had to appeal to when building this library using just the standard capabilities of Swift language.