Reactive testing for Shiny server functions and modules — testServer

testServer(app = NULL, expr, args = list(), session = MockShinySession$new())

Arguments

app

The path to an application or module to test. In addition to paths, applications may be represented by any object suitable for coercion to an appObj by as.shiny.appobj. Application server functions must include a session argument in order to be tested. If app is NULL or not supplied, the nearest enclosing directory that is a Shiny app, starting with the current directory, is used.

expr

Test code containing expectations. The test expression will run in the server function environment, meaning that the parameters of the server function (e.g. input, output, and session) will be available along with any other values created inside of the server function.

args

Additional arguments to pass to the module function. If app is a module, and no id argument is provided, one will be generated and supplied automatically.

session

The MockShinySession object to use as the reactive domain. The same session object is used as the domain both during invocation of the server or module under test and during evaluation of expr.

Description

A way to test the reactive interactions in Shiny applications. Reactive interactions are defined in the server function of applications and in modules.

Examples

server <- function(id, multiplier = 2, prefix = "I am ") {
  moduleServer(id, function(input, output, session) {
    myreactive <- reactive({
      input$x * multiplier
    })
    output$txt <- renderText({
      paste0(prefix, myreactive())
    })
  })
}

testServer(server, args = list(multiplier = 2), {
  session$setInputs(x = 1)
  # You're also free to use third-party
  # testing packages like testthat:
  #   expect_equal(myreactive(), 2)
  stopifnot(myreactive() == 2)
  stopifnot(output$txt == "I am 2")

  session$setInputs(x = 2)
  stopifnot(myreactive() == 4)
  stopifnot(output$txt == "I am 4")
  # Any additional arguments, below, are passed along to the module.
})