I'm in the process of working out how to unit test SwiftUI view code.
I have the following definition:
struct ContentView : View {
var body: some View {
Text("Hello World")
.font(.title)
.fontWeight(.bold)
}
}
and I can test it like this:
func testBody() {
let cv = ContentView()
let body = cv.body
XCTAssertNotNil(body)
guard let text = body as? Text else { XCTFail(); return }
XCTAssertEqual(Text("Hello World").font(.title).fontWeight(.bold), text)
}
however, as soon as I want to test text alignment, I run into issues:
production code:
struct ContentView : View {
var body: some View {
Text("Hello World")
.font(.title)
.fontWeight(.bold)
.multilineTextAlignment(.leading)
}
}
and test code:
func testBody() {
let cv = ContentView()
let body = cv.body
XCTAssertNotNil(body)
guard let text = body as? Text else { XCTFail(); return }
// COMPILER ERROR ON NEXT LINE
XCTAssertEqual(Text("Hello World").font(.title).fontWeight(.bold).multilineTextAlignment(.leading), text)
}
...then I get the following compiler error:
Cannot convert value of type 'Text' to expected argument type '_ModifiedContent<Text, _EnvironmentKeyWritingModifier<HAlignment>>'
How do I test the alignment of the Text struct?