首页 > 解决方案 > 测试中的闪亮反应上下文

问题描述

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

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 会话中执行内部块,我会得到同样的错误。

标签: rshinytestthat

解决方案


具有未导出功能的解决方案flushReact

library(shiny)

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

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

推荐阅读