shiny icon indicating copy to clipboard operation
shiny copied to clipboard

Within a testServer, isRunning() is not TRUE

Open taekeharkema opened this issue 2 years ago • 4 comments

Reprex

Code below results in an error:

library(shiny)
custom_function <- function() {
  if (!shiny::isRunning()) {
    stop("Shiny is not running")
  }
}

server <- function(input, output, session) {
  custom_function()
}

shiny::testServer(server, {
  session$setInputs(a = 2)
})

# Error in custom_function() : Shiny is not running 

Expected behaviour

I would expect shiny::isRunning() to be TRUE, even if the app is just a mock-up used within a test, and therefore the test to pass.

Describe the problem in detail

I'm trying to write a unit test for a function in a package that uses shiny::isRunning to determine whether the use of the function is appropriate. I want to test the behaviour of the function, but can't see a way, as the function throws an error when used within the testServer.

taekeharkema avatar Mar 07 '22 21:03 taekeharkema

A workaround could be to set the shiny .globals$appState to be not null, then clear it back to null at the end of the test

library(shiny)
custom_function <- function() {
  if (!shiny::isRunning()) {
    stop("Shiny is not running")
  }
}

server <- function(input, output, session) {
  
  shiny:::initCurrentAppState('testing')
  on.exit(shiny:::clearCurrentAppState(), add = TRUE)
  
  custom_function()
  
}

shiny::testServer(server, {
  session$setInputs(a = 2)
})

chwpearse avatar Mar 11 '22 09:03 chwpearse

Thanks, @chwpearse. That is a nice work-around. Still, I feel like the current behaviour is unexpected, and that I shouldn't have to depend on internal state.

taekeharkema avatar Mar 22 '22 09:03 taekeharkema

Might this be related to #3499?

klmr avatar May 11 '22 13:05 klmr

Hi @klmr,

I'm not sure, but don't think so. For the above reprex to run in shiny v1.5.0, I'd have to adapt the testServer call to:

shiny::testServer(app = function(id) {
  moduleServer(id, server)
  }, {
    session$setInputs(a = 2)
  })

But that results in the same Error in custom_function() : Shiny is not running.

So apparently this particular example is no regression from v1.5.0.

taekeharkema avatar May 13 '22 12:05 taekeharkema