I am writing UI tests and I need to access a view's @State properties, as long as a button inside this view.
struct CircleImage: View {
@State var imageName: String = ""
var body: some View {
// ...
Button(action: {}) {}
.accessibility(identifier: "myButton")
}
}
As is I easily get the button with let myButton = app.buttons["myButton"]
. But for testing purposes I also need the access to the imageName
property. I tried adding CircleImage().accessibility(identifier: "circleImageView")
in the ContentView, but it overwrites all the accessibility(identifier: ) inside the CircleImage view (including the button).
UI tests do not test internal state. They only test UI-visible behaviors. To write a UI test against this type, the imageName should result in some behavior, and you then test that the behavior is visible. In this case, you might make the imageName translate to an accessibility label, which would allow VoiceOver to read it (and incidentally also allow UI tests to access it).
The best way to make an app UI-testable is to first make it accessible. Try out your app with VoiceOver. If it works well there, then it will likely also work well for UI testing.