2

I am trying to add a snapshot test for a SwiftUI view that is using Core Data to drive the UI via the @FetchRequest property wrapper. I would like to add a small bit of logic within the UI and would like to have some snapshot tests to cover it.

Below is a snippet example of the SwiftUI view that I am trying to test.

struct TeamView: View {
    @Environment(\.managedObjectContext) var viewContext
    
    @FetchRequest(sortDescriptors: [SortDescriptor(\.name)])
    private var teams: FetchedResults<Team>
    
    var body: some View {
        NavigationView {
            List {
                ForEach(teams, id: \.id) { team in
                   Text(team.name)
                }
            }
            .navigationTitle(Text(TabItem.team.title))
        }
    }
}

Any ideas how I can create Team Objects that can then be used within TeamView to enable testing?

malhal
  • 26,330
  • 7
  • 115
  • 133
Edward
  • 2,864
  • 2
  • 29
  • 39
  • 2
    Approach can be the same as in https://stackoverflow.com/a/61495490/12299030. – Asperi Jun 28 '22 at 19:29
  • 1
    If you create a new CoreData Project with Xcode. In the `Persistence.swift` file you will find sample code for a `preview` context. You can create objects in that context as demonstrated there. – lorem ipsum Jun 28 '22 at 22:36
  • 1
    Worth noting that while state in the preview context is poss - as per Apple's demo code - its design intent is primarily to preview what the UI looks like as the developer codes, i.e. not intended as a test environment and doesn't scale well (e.g. how to deal with `@SceneStorage`, `@FocusState` etc). A better approach for seeing what state looks like in the UI is to split Views into a top-level state only injector View and one or more pure, stateless sub-Views with previews (as per-Asperi's suggested link). Works well to test non-apple code, if mixed with unit and app UI tests as needed. – shufflingb Jun 29 '22 at 11:31
  • I think you have to tell us what the logic you want to test so we can suggest the appropriate place to put it. – malhal Jul 01 '22 at 08:41

0 Answers0