swift-snapshot-testing icon indicating copy to clipboard operation
swift-snapshot-testing copied to clipboard

sizeThatFits does not work for some views in SwiftUI

Open btalyta opened this issue 4 years ago • 3 comments

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:

BarChartViewTest 1

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:

Captura de Tela 2020-06-23 às 11 03 40

But in the test this is the snapshot generated:

WrnInfoCard_testInterfaceStyleLight 1

btalyta avatar Jul 03 '20 16:07 btalyta

Also facing a lot of problems trying to snapshot SwiftUI views

txaiwieser avatar Jul 03 '20 16:07 txaiwieser

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:

testSnapshots 1

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:

testSnapshots 1

kmeinh avatar Sep 25 '20 09:09 kmeinh

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.

simondelphia avatar Jan 14 '22 04:01 simondelphia