You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测Shiny应用正由shinytest运行,以规避rhandsontable适配bug?

解决方案

你可以通过两种方式判断当前Shiny应用是否处于shinytest测试运行状态,实现你需要的分支逻辑:

方法1:使用shinytest内置检测函数

shinytest官方提供了shinytest::is_testing()函数,专门用于检测当前运行环境是否为shinytest测试环境,可直接调用:

if (shinytest::is_testing()) {
  output[["hot2"]] <- renderRHandsontable({
    rhandsontable(head(iris))
  })
} else {
  output[["hot2"]] <- renderRHandsontable({
    rhandsontable(head(iris)) %>%
      hot_validate_numeric(col = 1, min = 0, max = 100)
  })
}

方法2:直接检测环境变量(无额外包依赖)

如果你不想在生产环境的代码中引入shinytest包的调用,可以直接检测shinytest运行时自动设置的环境变量SHINYTEST,效果和上述方法完全一致:

# 环境变量SHINYTEST在shinytest运行时会被设为"1"
shinytestIsRunning <- identical(Sys.getenv("SHINYTEST"), "1")

if (shinytestIsRunning) {
  output[["hot2"]] <- renderRHandsontable({
    rhandsontable(head(iris))
  })
} else {
  output[["hot2"]] <- renderRHandsontable({
    rhandsontable(head(iris)) %>%
      hot_validate_numeric(col = 1, min = 0, max = 100)
  })
}

内容的提问来源于stack exchange,提问作者Stéphane Laurent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 05:27:01