End-to-end Shiny tests with shinytest2
Automate browser interactions, DOM verification, and reactive assertions using headless Chrome
The problem
Unit tests written with {testthat}—as covered in the first post in this series and in our discussion of test fixtures and mocking—verify isolated data transformations and business logic. The previous post covered testServer(), which tests server-side reactivity directly in memory. Running in milliseconds without launching a network server or a browser, testServer() is ideal for verifying reactive calculations, internal session state, and output expressions.
Yet testServer() never executes code in a client browser. This leaves substantial blind spots:
- No DOM or HTML rendering:
testServer()computes output values, but it never renders them into actual Document Object Model (DOM) nodes. Missing HTML tags, malformed layouts, missing CSS assets, or mismatched element IDs remain completely undetected. - No JavaScript execution: Client-side widgets such as interactive tables, plotting canvases, dynamic UI insertions, and custom JavaScript input bindings depend entirely on the browser’s JavaScript engine. Any custom event handler calling
Shiny.setInputValue()in JavaScript never runs undertestServer(). - No bookmarking or URL state: Applications that restore state through URL query parameters or
enableBookmarking()rely on browser navigation events and client-to-server synchronization. - No WebSocket protocol testing: The WebSocket handshake, reconnection logic, message serialization, and client latency cannot be observed without a running client-server pair.
When teams lack automated end-to-end testing, they fall back on manual browser verification. A developer launches the app locally, manually selects dropdown values, enters dates, verifies counts by eye, and repeats the routine across multiple browsers before every release. This manual process is slow, unrecorded, prone to oversight, and impossible to automate within continuous integration pipelines.
The web-repo way
In modern web development, end-to-end (E2E) testing relies on browser automation engines such as Playwright or Cypress. In a TypeScript application, unit test runners verify functions in isolation, while Playwright launches real headless browsers (Chromium, Firefox, or WebKit) to drive the full user journey:
// tests/e2e/safety-summary.spec.ts
import { test, expect } from "@playwright/test";
test("updates safety subject count when treatment arm changes", async ({ page }) => {
await page.goto("http://localhost:3000");
// Verify initial selection and rendered count
await expect(page.locator("#subject_count")).toHaveText("86");
// Select a new treatment arm and assert updated DOM text
await page.selectOption("#arm", "Xanomeline High Dose");
await expect(page.locator("#subject_count")).toHaveText("72");
});Web repositories structure automated browser testing around three core principles:
- Full-stack fidelity: The application runs as a real web server communicating over HTTP and WebSockets with a real browser engine.
- Deterministic synchronization: The test driver automatically awaits DOM updates, network traffic, and rendering stabilization before evaluating assertions, avoiding flaky timeouts.
- Headless automation in CI: Real headless browsers run on every pull request, turning user journeys into merge-blocking regression gates.
The R way
In R, {shinytest2} brings end-to-end browser testing to Shiny applications. Replacing the older PhantomJS-based {shinytest} package, {shinytest2} uses {chromote} to control headless Google Chrome or Chromium via the Chrome DevTools Protocol (CDP).
The core orchestrator: shinytest2::AppDriver
Every {shinytest2} test revolves around an instance of the AppDriver R6 class. An AppDriver object starts a background R process hosting your Shiny application, launches a headless Chrome session, navigates to the application URL, and coordinates interactions between testthat and the browser.
Here are the seven primary methods on AppDriver:
AppDriver$new(app_dir = ...): Initializes the background Shiny process and connects headless Chrome. Important arguments include:app_dir: Path to the directory containingapp.R.name: An optional identifier used to prefix snapshot files.seed: An optional numeric seed passed to the background process for reproducibility.wait = TRUE: Blocks initialization until the Shiny app reaches its initial idle state.check_names = TRUE: Validates that all HTMLinputandoutputIDs are unique, catching duplicate identifier bugs before user interactions begin.view: Set toTRUEto watch Chrome run visually during local debugging.
$set_inputs(...): Programmatically updates one or more inputs in the browser. To avoid collisions between Shiny input IDs and parameter names,{shinytest2}reserves trailing underscores for its internal control arguments:wait_ = TRUE(the default) instructsAppDriverto pause execution until the Shiny reactive graph completes recalculating and all affected outputs are rendered in the browser.timeout_defines the maximum wait duration before timing out.allow_no_input_binding_(defaultFALSE): setTRUEto allow setting a value on an input that has no Shiny input binding.priority_ = c("input", "event")specifies event priority.
$get_value(input = , output = , export = ): Retrieves a single scalar or data structure from the running application. You must provide exactly one ofinput,output, orexportas a string name. For example,app$get_value(output = "subject_count")returns the current rendered text value of that output.$get_values(input = , output = , export = ): Returns a named list containing all current reactive values across$input,$output, and$export. Passing specific variable names orTRUEfilters the returned list to selected scopes.$expect_values(): Creates or compares a JSON snapshot of reactive values (similar totestthat::expect_snapshot_value(), covered in snapshot testing). It serializes the specified inputs, outputs, and exports to a.jsonfile intests/testthat/_snaps/. In addition, it saves a debug screenshot ending in_.png. This debug image aids human visual inspection during pull request reviews, but differences in the image never fail the test.$wait_for_idle(duration = 500, timeout = ...): Explicitly halts the test execution until Shiny has remained idle (with no pending WebSocket messages or reactive computations) fordurationmilliseconds (default 500 ms).$stop(): Terminates the background Shiny R process and closes the Chrome session. Registerwithr::defer(app$stop())right after creating the driver, so the app and Chrome are stopped even if the test errors part-way through. (A failed expectation does not stop a test — only an error does — but you still want the driver cleaned up on that error path.)
Snapshot files versus visual screenshots
When {shinytest2} runs snapshot tests via $expect_values(), the captured JSON state files are stored under:
tests/testthat/_snaps/<test_file>/<name>-001.json
While AppDriver also provides an $expect_screenshot() method for comparing pixel-by-pixel images of the rendered UI, pixel screenshots often differ between machines (fonts, anti-aliasing, rendering), so a screenshot recorded on one OS can fail on another. Common causes include:
- Differences in system font packages and font rendering engines.
- Subtle anti-aliasing variations across operating systems.
- Variations in how Chrome paints borders, SVG curves, or drop shadows on different graphics architectures.
- Incomplete CSS transition or animation frames.
For resilient test suites, prefer testing underlying data values rather than pixels. Assert rendered text directly using $get_value() with expect_equal(), snapshot structured state with $expect_values(), or expose reactive objects directly using shiny::exportTestValues().
Runtime cost and the testing pyramid
End-to-end tests provide high fidelity, but they come with a runtime cost:
- A
testServer()test typically completes in milliseconds because it operates entirely within the current R process. - A
shinytest2test takes noticeably longer — seconds rather than milliseconds — because it must spawn a background R process, launch headless Chrome via{chromote}, establish a WebSocket connection, and wait for browser DOM stabilization.
Follow the testing pyramid strategy:
- Base (Unit tests): Write unit tests with
testthatfor pure business logic and data transformations (such as derivation functions or statistical formatting). - Middle (
testServer): Test complex reactive calculations, module communication, and reactive branching in memory withtestServer(). - Top (
shinytest2): Reserveshinytest2for high-value end-to-end user journeys: critical onboarding flows, bookmarking restoration, file download generation, and integration across custom JavaScript components.
Running in continuous integration (CI)
Executing {shinytest2} in continuous integration requires a Chrome or Chromium browser executable. Standard GitHub Actions virtual runners (ubuntu-latest, macos-latest, and windows-latest) include Google Chrome in their default system images.
CRAN build machines, however, do not provide an external Chrome executable, so {shinytest2} automatically calls testthat::skip_on_cran() inside AppDriver$new() — any test that creates an AppDriver already skips on CRAN. A separate skip_on_cran() in your test file is optional; what you do need to check yourself is Chrome’s availability with chromote::find_chrome():
# tests/testthat/test-app-e2e.R
library(shinytest2)
test_that("application loads and updates count", {
skip_if_not(nzchar(chromote::find_chrome()))
app <- AppDriver$new(testthat::test_path("../../inst/app"), name = "e2e")
withr::defer(app$stop())
app$expect_values()
})That same skip_on_cran() check reads the NOT_CRAN environment variable, which matters well outside of CRAN: without NOT_CRAN = "true" set, AppDriver$new() skips the test everywhere, not just on CRAN. Run Rscript -e 'testthat::test_dir("tests/testthat")' (or any CI job that doesn’t set it) and every shinytest2 test silently reports as skipped rather than run. Two ways to make sure it is set:
- In a GitHub Actions workflow, add
NOT_CRAN: trueunder the job or step’senv:. Ther-lib/actions/setup-raction already setsNOT_CRAN=truefor the whole job, so anR CMD checkjob on GitHub runs the browser tests that CRAN skips. - In a standalone script, as this post’s companion script does:
withr::local_envvar(NOT_CRAN = "true")before creating theAppDriver. Never put this in a package’stests/testthat/files: it would switchskip_on_cran()off on CRAN too, where there is no Chrome, so the test would error instead of skipping andR CMD checkwould fail.
If you drive your package tests with devtools::test(), this is already handled — it sets NOT_CRAN = "true" (unless you’ve set it to something else) before running your test suite.
Worked clinical example: ADSL safety summary
Consider a clinical trial application that displays subject counts from pharmaverseadam::adsl. In clinical reporting, summarizing demographics or adverse events begins with the safety population (SAFFL == "Y").
We inspect the actual safety population counts by treatment arm (TRT01A):
# Baseline counts from ADSL safety population
saf_data <- subset(pharmaverseadam::adsl, SAFFL == "Y")
table(saf_data$TRT01A)The safety population consists of 86 subjects on Placebo, 72 on Xanomeline High Dose, and 96 on Xanomeline Low Dose.
We define a minimal Shiny application that allows a user to select a treatment arm and view the corresponding count:
library(shiny)
ui <- fluidPage(
titlePanel("Safety Population Summary"),
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "arm",
label = "Treatment Arm",
choices = c("Placebo", "Xanomeline High Dose", "Xanomeline Low Dose"),
selected = "Placebo"
)
),
mainPanel(
h4("Safety Subjects (SAFFL == Y)"),
textOutput("subject_count")
)
)
)
server <- function(input, output, session) {
output$subject_count <- renderText({
req(input$arm)
saf <- subset(pharmaverseadam::adsl, SAFFL == "Y" & TRT01A == input$arm)
as.character(nrow(saf))
})
}Now we write an automated end-to-end test with AppDriver to verify the full user workflow:
# tests/testthat/test-adsl-app.R
library(shinytest2)
test_that("ADSL safety summary updates displayed count on arm selection", {
skip_on_cran()
skip_if_not(nzchar(chromote::find_chrome()))
app <- AppDriver$new("path/to/app", name = "adsl-summary")
withr::defer(app$stop())
# 1. Verify initial count for default selection (Placebo)
expect_equal(app$get_value(output = "subject_count"), "86")
# 2. Select Xanomeline High Dose and assert updated reactive count
app$set_inputs(arm = "Xanomeline High Dose")
expect_equal(app$get_value(output = "subject_count"), "72")
# 3. Select Xanomeline Low Dose and assert updated reactive count
app$set_inputs(arm = "Xanomeline Low Dose")
expect_equal(app$get_value(output = "subject_count"), "96")
# 4. Verify complete input/output state
vals <- app$get_values()
expect_equal(vals$input$arm, "Xanomeline Low Dose")
expect_equal(vals$output$subject_count, "96")
})When evaluated, AppDriver launches Chrome headlessly, changes the selected arm via the browser’s input binding, waits for Shiny to finish reactive recalculations (wait_ = TRUE), and asserts that the exact string rendered in the browser DOM matches our clinical dataset.
Companion code
View app-driver-demo.R · Download
Writes a clinical safety Shiny application to a temporary directory, launches Chrome headlessly with shinytest2::AppDriver, asserts rendered DOM outputs against pharmaverseadam::adsl, and stops the application. Requires {shinytest2}, {shiny}, {pharmaverseadam}, and {withr}.
app-driver-demo.R
# End-to-end Shiny testing with shinytest2 and AppDriver
#
# Writes a Shiny application summarizing clinical trial safety subjects
# (pharmaverseadam::adsl where SAFFL == "Y") by treatment arm, drives it
# headlessly with shinytest2::AppDriver, asserts initial and updated output
# values, and cleanly stops the application.
#
# Run with:
# Rscript app-driver-demo.R
#' Write the ADSL summary Shiny application to disk
#'
#' @param app_dir Directory where app.R will be written.
#' @return The application directory path, invisibly.
#' @export
write_adsl_app <- function(app_dir) {
if (!dir.exists(app_dir)) {
dir.create(app_dir, recursive = TRUE)
}
app_code <- c(
"library(shiny)",
"",
"ui <- fluidPage(",
" titlePanel(\"Safety Population Summary\"),",
" sidebarLayout(",
" sidebarPanel(",
" selectInput(",
" inputId = \"arm\",",
" label = \"Treatment Arm\",",
" choices = c(\"Placebo\", \"Xanomeline High Dose\", \"Xanomeline Low Dose\"),",
" selected = \"Placebo\"",
" )",
" ),",
" mainPanel(",
" h4(\"Safety Subjects (SAFFL == Y)\"),",
" textOutput(\"subject_count\")",
" )",
" )",
")",
"",
"server <- function(input, output, session) {",
" output$subject_count <- renderText({",
" req(input$arm)",
" saf <- subset(pharmaverseadam::adsl, SAFFL == \"Y\" & TRT01A == input$arm)",
" as.character(nrow(saf))",
" })",
"}",
"",
"shinyApp(ui = ui, server = server)"
)
writeLines(app_code, file.path(app_dir, "app.R"))
invisible(app_dir)
}
#' Calculate expected safety subject count from ADSL
#'
#' @param arm Treatment arm (TRT01A).
#' @return Integer subject count.
#' @export
compute_safety_count <- function(arm) {
sum(
pharmaverseadam::adsl$SAFFL == "Y" &
pharmaverseadam::adsl$TRT01A == arm,
na.rm = TRUE
)
}
#' Drive the ADSL application with AppDriver
#'
#' @param app_dir Directory containing the Shiny application.
#' @return Named list with recorded values from AppDriver.
#' @export
run_app_driver_demo <- function(app_dir) {
withr::local_envvar(NOT_CRAN = "true")
app <- shinytest2::AppDriver$new(app_dir, name = "adsl-summary")
withr::defer(app$stop())
initial_val <- app$get_value(output = "subject_count")
app$set_inputs(arm = "Xanomeline High Dose")
high_dose_val <- app$get_value(output = "subject_count")
app$set_inputs(arm = "Xanomeline Low Dose")
low_dose_val <- app$get_value(output = "subject_count")
list(
placebo = initial_val,
high_dose = high_dose_val,
low_dose = low_dose_val
)
}
# Run demo only when executed directly as a script.
if (sys.nframe() == 0L) {
message("Writing ADSL safety summary app to temporary directory...")
demo_dir <- withr::local_tempdir()
write_adsl_app(demo_dir)
message(
"Starting AppDriver and testing reactive outputs in headless Chrome..."
)
results <- run_app_driver_demo(demo_dir)
message("Initial (Placebo) count: ", results$placebo)
message("Updated (High Dose) count: ", results$high_dose)
message("Updated (Low Dose) count: ", results$low_dose)
message("AppDriver stopped cleanly. Demo complete.")
}Sources
Package documentation
- r-lib/actions
setup-r: README - shinytest2: CRAN
- chromote: CRAN
- testthat: testthat.r-lib.org
- withr: withr.r-lib.org
- pharmaverseadam: pharmaverse.github.io/pharmaverseadam
Web-repo comparison
- Playwright: playwright.dev
- 2026-09-27: Added a Sources section.
- 2026-09-27: Added a Companion code section with the full script.
- 2026-11-13: The in-file
NOT_CRANoverride is for standalone scripts only, never package tests, because it makes the test error on CRAN instead of skipping. Added thatsetup-rsetsNOT_CRAN=trueby default.