Tuesday, January 26, 2021 [Tweets] [Favorites]

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:

  1. All types in reflection are erased to Any
  2. Computed properties, such as var body: some View, are not available in reflection
  3. Generic private structs and function types which are tricky to cast the value to
  4. Initializing a struct which all init methods are private
  5. SwiftUI dependency injection through Environment
  6. Property wrappers, such as @State, with an elusive storage for values
  7. Significant variations of the hierarchy after a tiny tweak of the input. For example, Text("Hi") vs Text(hiValue)
  8. 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.

Comments

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment