How does xcode find PreviewProviders to show previews

I had this idea that it would be cool to combine snapshot testing with previews, so the developer only had to write previews once, and they would get snapshot tests for free. To do this I would need a way of enumerating the PreviewProviders (ideally inside of a test target, but that's not a hard requirement could be an external process).

So my question, any idea how xcode is able to find the PreviewProviders? Unlike XCTest which is able to use the ObjectiveC runtime to find tests, PreviewProviders are pure swift.

2 Likes

Looks like I may be able to use sourcery to automatically generate snapshot tests.

Using this template I got the names of all the PreviewProviders. I should be able to expand this to generate XCTest backed snapshot tests.

<% for type in types.types where type.inheritedTypes.contains("PreviewProvider") { -%>
  <%_ %><%= type.name %>
<% } %>

I'd guess that Xcode is using SourceKit to obtain the PreviewProvider conforming types that exist in the open file.

Be aware that Xcode only finds top level PreviewProviders, while that sourcery template probably finds all of them

Terms of Service

Privacy Policy

Cookie Policy