SwiftUI Snapshot test async view

1k Views Asked by At

I am following this page in creating a wrapped HStack. However, the HStack asynchronously calculates its height, which means my snapshot testing become really funky. I looked at this episode on asynchronous snapshot testing but it wasn't too clear/helpful.

Could someone help shed light on how to use the SwiftUI Snapshot Testing Library (https://github.com/pointfreeco/swift-snapshot-testing) to test my new (somewhat asychronous) Wrapped HStack?

I followed this Gist and used this code to create the snapshot test:

    func test_wrappingHStack() {
        let view = ScrollView {
            VStack {
                Text("Title").font(.headline)
                WrappingHStack(models: ["Ninetendo", "XBox", "PlayStation", "PlayStation 2", "PlayStation 3", "PlayStation 4", "Apple", "Google", "Amazon", "Microsoft", "Oracle", "Facebook"]) { str in
                    Text(str)
                }
                Button("Click me") {}
            }
        }
        assertSnapshot(matching: view.toViewController(), as: .image, record: true)
    }

extension SwiftUI.View {
    func toViewController() -> UIViewController {
        let viewController = UIHostingController(rootView: self)
        viewController.view.frame = UIScreen.main.bounds
        return viewController
    }
}

The screenshot I get from the test is: blank image

1

There are 1 best solutions below

0
On

This page: https://www.pointfree.co/blog/posts/23-snapshottesting-1-0-delightful-swift-snapshot-testing#:~:text=Async%20snapshots&text=A%20common%20example%20is%20WKWebView,value%20into%20the%20diffable%20format.

Talks about how to test an asynchronous view. It's a bit complex because you have to create the diffable view yourself:

When creating a Snapshotting<Value, Format> value you can provide a function (Value) -> Async, which allows you to asynchronously turn your value into the diffable format