Unit testing SwiftUI with ViewInspector
Unit testing or test-driven development are not buzzwords anymore, and in the iOS ecosystem, they are almost taken for granted. Any iOS developer should know about test tools and how to apply them.
XCTest and XCUITest are mature frameworks, and so you'd expect to have something similar for SwiftUI.
Unfortunately, SwiftUI doesn't come with any test capabilities from Apple. To test a SwiftUI view, you could rely on either UI testing, which is flaky by nature, or use snapshot testing, as you can see in the Snapshot testing SwiftUI views recipe.
However, the beauty of open source is that given a problem, the community somehow finds a solution. This is the case with SwiftUI unit testing and ViewInspector
, a framework for the inspection and testing of SwiftUI views.
In this recipe, we'll implement a simple SwiftUI view with some interaction, and we'll see how to test its structure and activity.
Getting ready
Let...