nalexn / ViewInspector

Runtime introspection and unit testing of SwiftUI views
MIT License
2.09k stars 145 forks source link

Runtime warning when using . modelContainer modifier for SwiftData #272

Closed sisoje closed 5 months ago

sisoje commented 7 months ago

I am using SwiftData and writing some tests. I noticed a runtime warning: Accessing StateObject's object without being installed on a View. This will create a new instance each time.

The test is:

    func testSD() throws {
        struct VVV: View {
            var inspect: ((Self) -> Void)?
            var body: some View { EmptyView().onAppear { inspect?(self) } }
        }
        var model = VVV()
        let exp = model.on(\.inspect) { _ in }
        ViewHosting.host(
            view: model.modelContainer(for: Item.self, inMemory: true)
        )
        wait(for: [exp], timeout: 0.1)
    }

Note that the view is completely empty. Only by applying modifier .modelContainer the warning shows.

Here is the warning: Screenshot 2023-11-13 at 13 13 18

sisoje commented 7 months ago

I found the workaround, instead of:

        ViewHosting.host(
            view: model.modelContainer(for: Item.self, inMemory: true)
        )

I use this

        ViewHosting.host(
            view: model.environment(\.modelContext, context)
        )