swift-snapshot-testing
swift-snapshot-testing copied to clipboard
sizeThatFits does not work for some views in SwiftUI
Hello guys, I was using .sizeThatFits to capture the snapshot but I found two problems in the generated images.
assertSnapshot(matching: sut, as: .image(layout: .sizeThatFits, traits: .init(userInterfaceStyle: .light)))

In the first case some views have the following error:
However, in the Xcode preview, the view is correctly rendered. And in the second case for some views the generated image was not the expected size. In the Xcode preview I get this result:

But in the test this is the snapshot generated:
Also facing a lot of problems trying to snapshot SwiftUI views
Hey,
just played around with SwiftUI + Snapshot Tests today, and also came across this behavior. Problem is that your text can shrink and the Tests try to fit your View in a small box (0 by 0).
so let's say you have a MyButton like so:
Button(action: someAction) {
Text(someText)
.padding()
.foregroundColor(.white)
}
.background(Color.blue)
.cornerRadius(6)
your test might now look like this:
let content = MyButton("very long Text\nwith second line")
assertSnapshot(matching: content, as: .image())
output:
Fix:
Fix the content size after creating it to prevent the Test from resizing it.
This is mainly for layout: .sizeThatFits - default of .image()
let content = MyButton("very long Text\nwith second line").fixedSize(horizontal: true, vertical: true)
assertSnapshot(matching: content, as: .image())
output:
Is there no way to make this the default behaviour? Seems annoying to have to remember to put .fixedSize() anytime you want to snapshot a SwiftUI view? I suppose one could make a convenience method to replace assertSnapshot.