rstudio / shinytest2

https://rstudio.github.io/shinytest2/
Other
106 stars 18 forks source link

Capturing a `validate(need(......))` message located inside a `reactive()` #333

Open stla opened 1 year ago

stla commented 1 year ago

Hello,

As far as I know, putting validate(need(......)) inside a reactive conductor is a valid practice. However that causes a problem with shinytest2: the test fails because of an error whenever one calls app$get_value() or app$get$values().

library(shiny)
library(ggplot2)
ui <- fluidPage(
  numericInput("n", "Number of rows", 10, 1, nrow(cars)),
  plotOutput("plot")
)
server <- function(input, output) {
  dt <- reactive({
    head(cars, input$n)
  })

  plot_obj <- reactive({
    validate(need(input$n > 0, message = "n must be strictly positive"))
    ggplot(dt(), aes(speed, dist)) + geom_point()
  })

  output$plot <- renderPlot({
    plot_obj()
  })

  exportTestValues(
    dt = dt(),
    plot_obj = plot_obj()
  )
}

shinyApp(ui = ui, server = server)
app <- AppDriver$new()
app$set_inputs(n = 0)
app$get_values()
stla commented 1 year ago

Sorry, in fact app$get_value(output = "plot") works fine. The error appears when calling app$get_value(export = plot_obj).

> app$get_value(export = "plot_obj")
{shinytest2} query failed (500)----------------------
URL: http://127.0.0.1:3372/session/ee5d1f45139583f822803a4f41015321/dataobj/shinytest?w=&nonce=eca19e590&&&export=plot_obj&format=rds&sortC=1
<html>

<head lang = "en">
  <title>An error has occurred</title>
</head>

<body>

<h1>An error has occurred!</h1>
<p>n must be strictly positive</p>

</body>
</html>
schloerke commented 1 year ago

I can reprex. Thank you!


Workaround for now...

  exportTestValues(
    dt = dt(),
    plot_obj = tryCatch(plot_obj(), error = function(e) e)
  )

I'll make a PR in rstudio/shiny