【问题标题】:Shiny Reactive Context in testthat test测试中的闪亮反应上下文
【发布时间】:2021-02-09 12:02:47
【问题描述】:

我正在尝试执行需要反应式上下文的代码(但不是整个服务器)

library(shiny)
library(testthat)

test_that("test ", {
  withReactiveDomain(MockShinySession$new(), {
    v <- reactiveVal()
    v("abc")
    val <- v()
    expect_equal("abc", val)
  })
})

然后我得到以下错误:

Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
Backtrace:
 1. shiny::withReactiveDomain(...) test_integration.R:45:2
 5. shiny:::v() test_integration.R:48:4
 6. rv$get()
 7. private$dependents$register()
 8. shiny:::getCurrentContext()
 9. .getReactiveEnvironment()$currentContext()

我错过了什么?如果我在 R 会话中执行内部块,我会得到同样的错误。

【问题讨论】:

  • 虽然我需要更好地理解withReactiveDomain 的内部结构:像val &lt;- isolate(v()) 这样隔离赋值可以让你的测试通过。如果这对您来说已经足够了,我可以提交此评论作为答案。

标签: r shiny testthat


【解决方案1】:

未导出函数flushReact的解决方案:

library(shiny)

x <- reactiveVal()
observe({
  message(x())
})
x("abc")

capture.output(shiny:::flushReact(), type = "message")
# [1] "abc"

【讨论】:

    【解决方案2】:

    @anddt 的解决方案

    library(shiny)
    library(testthat)
    
    test_that("test ", {
      withReactiveDomain(MockShinySession$new(), {
        v <- reactiveVal()
        v("abc")
        val <- isolate(v())
        expect_equal("abc", val)
      })
    })
    

    【讨论】:

      猜你喜欢
      • 2014-11-12
      • 2013-07-16
      • 2020-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-23
      • 2014-08-23
      • 2020-10-13
      相关资源
      最近更新 更多