doordash-oss / swiftui-preview-snapshots

Apache License 2.0
154 stars 7 forks source link

Minimal support for custom snapshot directory #8

Closed mackoj closed 5 months ago

mackoj commented 5 months ago

Having this public could allow us to use custom snapshot directory.

This code will allow us to fix #9.

jflan-dd commented 5 months ago

@mackoj, I think I'd like to leave this private since it's not really meant to be accessed in day-to-day use. It's a pretty trivial function and the Configuration.name is public, so you could easily duplicate it in your custom function that's calling down into verifySnapshot, assuming you're even using the name parameter in assertSnapshots.

mackoj commented 5 months ago

Yes, it’s true. It can work without this modification or be done elsewhere. Thanks.

I used this functionality because I simply copied and pasted your original implementation of assertSnapshot since you had used it.

My goal was more to demonstrate that it can be trivial to support the use of verifySnapshot instead of assertSnapshot and to gain the ability to change the snapshot directory.

I hope to have shown/shared a simple way, in issue #9, to support this feature that can be really helpful.

jflan-dd commented 5 months ago

@mackoj I think it's a great example, thanks for sharing it.

Seeing as using a custom snapshot directory with vanilla swift-snapshot-testing requires calling into verifySnapshot directly rather than using one of the assertSnapshot functions I think requiring the same approach in this library is reasonable.

As you've demonstrated it's possible for consumers of the library to implement their own custom snapshotting functions by looping over configurations directly:

extension PreviewSnapshots {
    func customAssertSnapshots(
        as snapshotting: Snapshotting<AnyView, UIImage> = .image,
        record recording: Bool = false,
        file: StaticString = #file,
        testName: String = #function,
        line: UInt = #line
    ) {
        for configuration in configurations {
            let failure = verifySnapshot(
                matching: configure(configuration.state),
                as: snapshotting,
                record: recording,
                snapshotDirectory: "/some/location"
            )
            if let message = failure {
                XCTFail(message, file: file, line: line)
            }
        }
    }
}
mackoj commented 5 months ago

Maybe adding a little bit of documentation could be enough to clarify how to utilize your library and assist people seeking this feature.

mackoj commented 5 months ago

In my example, I did use the same function name as you because I didn’t want to change all the tests; it was more convenient and blend perfectly since it's not the same function signature.