Skip to content

How to use a variable inside a shiny app? #303

Closed

Description

@daattali

I'm trying to create a unit test where I set a variable at the start of the {testthat} unit test and use that variable in a shiny app, then use {shinytest2} to test the app. However, it seems like I can't refer to that variable when wrapping my app in an AppDriver.

Example:

foo <- 5

app <- shiny::shinyApp(
  ui <- shiny::fluidPage(),
  server = function(input, output, session) {
    foo
  }
)

driver <- shinytest2::AppDriver$new(app)
driver$get_logs()

You'll see the error message object 'foo' not found

Activity

  1. daattali commented on Jan 9, 2023

    @daattali
    ContributorAuthor

    Upon further investigation, it seems like the problem is more nuanced. If you place foo inside the UI, then the app works fine. Placing foo inside the server causes the error.

    Perhaps related to #296

  2. schloerke commented on Jan 10, 2023

    @schloerke
    Collaborator

    I can duplicate the error if run in the R console.

    The error goes away if run within a testthat file.

    Are you running your code in the R console?


    I can get this to work as expected in the R console:

    app <- local({
      foo <- 5
      foo3 <- 19
    
      shiny::shinyApp(
        ui <- shiny::fluidPage(textOutput("foo")),
        server = function(input, output, session) {
          foo3
          foo2 <- foo + 1
          output$foo <- renderText({
            foo2
          })
        }
      )
    })
    
    driver <- AppDriver$new(app)
    driver$get_logs()
    

    If foo3 is outside of local() and run in the R console, it will fail.

    Fails:

    foo <- 5
    app <- local({
    
      foo3 <- 19
    
      shiny::shinyApp(
        ui <- shiny::fluidPage(textOutput("foo")),
        server = function(input, output, session) {
          foo3
          foo2 <- foo + 1
          output$foo <- renderText({
            foo2
          })
        }
      )
    })
    
    driver <- AppDriver$new(app)
    driver$get_logs()
    
  3. schloerke commented on Jan 10, 2023

    @schloerke
    Collaborator

    I believe I've found a fix. Will make a PR tomorrow.

  4. added
    bug
    on Jan 12, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions