单元测试闪亮的应用程序

Ash*_*dry 17 testing r shiny

所以我一直在编写一个相当详细的闪亮应用程序,并且将来需要更新,因为运行的功能背后不断变化.

我需要做的是进行单元测试(使用testthat或其他对闪亮应用程序更有用的库),使我能够以更自动化的方式运行这些测试.

我写了一个简单的闪亮应用程序.为了测试,我想知道如果我在数字输入中选择数字20,那么我得到400作为输出$ out文本.但是希望能够在没有实际运行应用程序的情况下执行此操作.

library(shiny)

ui <- fluidPage(title = 'Test App', 
    numericInput('num', 'Number', 50, 1, 100, 0.5),
    'Numeric output',
    textOutput('out')
)

server <- function(input, output, session) {
  aux <- reactive(input$num ^ 2)

  output$out <- renderText(aux())
}

shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

小智 5

正如许多人已经提到的那样,您可以将Shinytest软件包与testthat结合使用。

这里有个简单的例子:

library(shinytest)
library(testthat)

context("Test shiny app")

#open shiny app
app <- ShinyDriver$new('path_to_shiny_app')

test_that("app gets expected output", {
  #set numeric input
  app$setInputs(num = 20)
  #get output
  output <- app$getValue(name = "out")
  #test
  expect_equal(output, "400")  
})

#stop shiny app
app$stop()
Run Code Online (Sandbox Code Playgroud)


小智 1

我在这里看到两种潜在的方法 \xe2\x80\x93测试底层功能,并执行 Web 应用程序本身的测试。请注意,后者实际上需要运行服务器,但更准确地表示您的网络应用程序是否正常工作。

\n\n

通过测试底层功能,我的意思是将您当前在服务器中执行的计算重构为它们自己的独立功能。您应该将功能与服务器分开,以便对其进行测试,而不是直接在服务器中对数字进行平方。例如,像这样:

\n\n
square_of_number <- function(n) return(n^2)\n
Run Code Online (Sandbox Code Playgroud)\n\n

现在,您可以单独测试该square_of_number函数的预期输出。

\n\n
library(\'testthat\')\n\nsquare_of_number <- function(n) return(n^2)\n\nexpect_equal(square_of_number(4), 16)\n
Run Code Online (Sandbox Code Playgroud)\n\n

此外,如果您想测试应用程序本身,您还可以使用无头浏览器在使用 Shiny 生成的实际 UI 上创建测试。评论中建议的一种方法是使用Shinytest,但我建议尝试的一种方法是:

\n\n\n