Hi,
I'm trying to use the testServer()
function to run tests on my modularised app. The mini app, whose code is shown below contains a Go
button which when clicked, should display a text based on the three inputs provided. The text is stored in a reactive object which is then stored in output$displayed_text
. The test at the bottom of the script works well when when I disable the shiny::observeEvent()
function like I've done in the code, but it fails otherwise. NB: Due to the nature of our main app, {shinytest2}
is currently not an option. Assistance on this will be highly appreciated.
#' kwanza UI Function
#'
#' @description A shiny Module that contains code for the first tab.
#'
#' @param id,input,output,session Internal parameters for {shiny}.
#'
#' @noRd
#'
#' @importFrom shiny NS tagList
mod_kwanza_ui <- function(id){
ns <- NS(id)
shiny::tagList(
shiny::fluidPage(
shiny::textInput(ns("firstname"), "First name", value = NULL),
shiny::br(),
shiny::textInput(ns("secondname"), "Second name", value = NULL),
shiny::br(),
shiny::numericInput(ns("yob"), "Year of birth", value = NULL),
shiny::br(),
shiny::actionButton(ns("go_button"), "Go"),
shiny::br(),
shiny::br(),
shiny::textOutput(ns("displayed_text")),
shiny::br(),
shiny::br(),
shiny::actionButton(ns("kwanza_next"), "Next"),
)
)
}
#' kwanza Server Functions
#'
#' @noRd
mod_kwanza_server <- function(id){
moduleServer( id, function(input, output, session){
ns <- session$ns
# shiny::observeEvent(input$go_button, {
## activating this observeEvent makes the test fail with the error
##`Error in displayed_text_r() : could not find function "displayed_text_r"`
displayed_text_r <- shiny::reactive({
paste0("Hi ", input$firstname , " ", input$secondname ," ! " ,
"You are ", ceiling(lubridate::year(Sys.Date())- input$yob), " years old.")
})
output$displayed_text <- shiny::renderText({
displayed_text_r()
})
# })
})
}
## Uncomment these lines if you want to view the app.
# # Shiny App
# ui <- fluidPage(
# mod_kwanza_ui("kwanza_1")
# )
#
# server <- function(input, output, session) {
# mod_kwanza_server("kwanza_1")
# }
#
# # Run the Shiny App
# shinyApp(ui, server)
# test function
testServer(
mod_kwanza_server,
# Add here your module params
args = list()
, {
ns <- session$ns
session$setInputs(firstname = "Shel")
session$setInputs(secondname = "Kariuki")
session$setInputs(yob = 2000)
session$setInputs(go_button = 1) ## Is this right?
print(displayed_text_r()) #for my own sanity
testthat::expect_true(grepl( "Shel", displayed_text_r()))
})