SwiftUI and unit testing

Appologies for cross-posting but I just found the right forum to ask this question.


I am trying to write unit tests for SwiftUI views but finding zero resources on the web for how to go about that. Any pointers?

I have a view like the following

struct Page: View { 
@EnvironmentObject var service: Service
var body: some View {
NavigationView {
ScrollView(.vertical) {
VStack {
Text("Some text"))
.font(.body)
.navigationBarTitle(Text("Title")))
Spacer(minLength: 100)
}
}
}
}
}

I started writing a test like this

func testPage() { 
let page = Page().environmentObject(Service())
let body = page.body
XCTAssertNotNil(body, "Did not find body")
}

But then how do I get the views inside the body? How do I test their properties?

As a matter of fact even this doesn't work. I am getting the following runtime exception

Thread 1: Fatal error: body() should not be called on  ModifiedContent<Page,_EnvironmentKeyWritingModifier<Optional<Service>>>.

Replies

Take a look at this project. It gives you a way to inpsect the view hierarchy. Look at the test cases for plenty of examples.


https://github.com/nalexn/ViewInspector

  • its not apple recommended way of extracting views and test the child objects.

Add a Comment