skip to Main Content

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)
}

2

Answers


  1. Chosen as BEST ANSWER

    Alternatively I was able to solve the problem not using the #Preview macro.

    struct ErrorViewOk_Preview: PreviewProvider {
    enum MockError: Error {
        case invalidData
    }
    static var errorWrapper = ErrorWrapper(error: MockError.invalidData, guidance: "guidance", errorStyle: ErrorStyle.ok)
    
    static var previews: some View {
        ErrorViewOk(errorWrapper: errorWrapper)
    }
    

    }


  2. 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))
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search