xcodeswiftui

How to mock #Preview with a view expecting an Error as parameter?


I have a view showing error information which is working fine. The information is wrapped inside a struct. But I couldn’t figure out how to mock the expected data to show the view in preview canvas.

Struct to store the error information.

struct ErrorWrapper: Identifiable {
    let id = UUID()
    let error: Error
    let guidance: String
    let errorStyle: ErrorStyle
}

Preview with the missing part for the Error.

#Preview {
    //how to instanciate an error?
    static var errorWrapper = ErrorWrapper(error, "guidance", ErrorStyle.ok)
    ErrorViewOk(errorWrapper: errorWrapper)
}

Solution

  • Error is a protocol so you can create a mock concrete type for it, something like:

    enum MockError: Error {
        case invalidData
    }
    
    #Preview {
        ContentView(error: ErrorWrapper(MockError.invalidData,
                                        "Halo",
                                        ErrorStyle.ok))
    }