Shiny
R
Best practices
Testing series · part 4

Testing Shiny server logic with testServer()

Verify reactive calculations, module outputs, and inputs headless without a browser

Test Shiny modules and server logic headless with shiny::testServer(), verify reactive state and return values, and separate pure logic for testthat.
Published

2026-09-26

Modified

2026-09-27

The problem

Interactive Shiny applications rely on a reactive dependency graph: user inputs invalidate reactive expressions, observers execute, and outputs re-render.

Most teams test this interactively: start the app, wait for the browser, click dropdowns, and eyeball the result.

Interactive manual testing breaks down as applications grow:

  • Slow and unrepeatable: Navigating multi-tab workflows takes minutes, cannot run in CI, and leaves no record.
  • Unclear failure boundaries: When an exploratory click yields a wrong number, you cannot tell whether the fault lies in input serialization, data transformation, reactive invalidation, or HTML rendering.
  • Untested edge cases: Checking missing baselines or empty clinical subgroups requires tedious clicking that teams skip under deadline pressure.

Manual browser checking couples business calculations to browser rendering. We need headless, automated tests that isolate server logic from the web browser.

The web-repo way

Web engineering teams hit the same problem. Running browser suites with Playwright or Cypress for every calculation is slow and brittle.

Web engineering separates testing into three tiers:

  1. Pure domain logic: Data transformations and business rules live in pure TypeScript functions with no browser dependencies, tested with Vitest or Jest.
  2. Headless state and hook testing: Custom state hooks and state machines are tested in memory without opening a browser using @testing-library/react and renderHook:
// src/use-safety-filter.test.ts
import { renderHook, act } from "@testing-library/react";
import { useSafetyFilter } from "./use-safety-filter";
import { mockParticipants } from "./fixtures";

describe("useSafetyFilter", () => {
  it("filters participants and updates summary counts on arm change", () => {
    const { result } = renderHook(() => useSafetyFilter(mockParticipants));

    expect(result.current.selectedCount).toBe(254);

    act(() => {
      result.current.setArm("Placebo");
    });

    expect(result.current.selectedCount).toBe(86);
    expect(result.current.statusText).toBe(
      "Placebo: 86 of 254 subjects (safety population)"
    );
  });
});
  1. End-to-end browser tests: Real browsers verify page rendering, CSS layout, and user flows.

The middle tier—headless state testing—is fast, deterministic, and tests reactive transitions without browser overhead.

The R way

In R, {shiny} mirrors this three-tier architecture:

  1. Extract business logic into pure R functions tested with {testthat} (see testthat essentials).
  2. Test reactive wiring, inputs, observers, rendered outputs, and module return values headless in memory with shiny::testServer().
  3. Reserve end-to-end browser tests for visual rendering and user workflows.

1 · Separating pure domain logic from reactive wiring

The most useful rule for testable Shiny code: keep reactives thin.

When filtering and clinical derivations sit inside shiny::reactive() or shiny::renderText(), they cannot be tested without a reactive context.

Consider a clinical trial module that filters pharmaverseadam::adsl to the safety population (SAFFL == "Y") and calculates subject counts for a selected treatment arm (TRT01A). Extracting the domain logic into a pure R function leaves the calculation independent of Shiny:

#' Filter safety population and summarize treatment arm counts
summarize_safety_arm <- function(data, arm = "All") {
  if (!is.data.frame(data)) {
    stop("`data` must be a data frame.", call. = FALSE)
  }
  if (!all(c("SAFFL", "TRT01A") %in% names(data))) {
    stop("`data` must contain `SAFFL` and `TRT01A` columns.", call. = FALSE)
  }

  saffl_data <- data[!is.na(data$SAFFL) & data$SAFFL == "Y", , drop = FALSE]
  n_total <- nrow(saffl_data)

  if (identical(arm, "All")) {
    filtered <- saffl_data
  } else {
    filtered <- saffl_data[
      !is.na(saffl_data$TRT01A) & saffl_data$TRT01A == arm,
      ,
      drop = FALSE
    ]
  }

  list(
    data = filtered,
    n_arm = nrow(filtered),
    n_total = n_total,
    arm = arm
  )
}

This function, and the module functions shown later, are copied from the companion script (scripts/module-demo.R); a test fails if the copies ever differ. Because summarize_safety_arm() is a plain R function, you can write unit tests with standard testthat assertions without any Shiny session:

adsl <- pharmaverseadam::adsl

# Verify safety population filtering against baseline data
all_res <- summarize_safety_arm(adsl, arm = "All")
testthat::expect_equal(all_res$n_total, 254L)
testthat::expect_equal(all_res$n_arm, 254L)

# Verify treatment arm subsetting
pbo_res <- summarize_safety_arm(adsl, arm = "Placebo")
testthat::expect_equal(pbo_res$n_arm, 86L)
testthat::expect_equal(pbo_res$n_total, 254L)

# Verify input validation guardrails
testthat::expect_error(
  summarize_safety_arm(list()),
  "`data` must be a data frame."
)

With domain calculations tested directly, the module server only handles reactive orchestration:

2 · Headless module testing with testServer()

Shiny modules pair UI with server logic wrapped in shiny::moduleServer():

arm_filter_ui <- function(
    id,
    arms = c("All", "Placebo", "Xanomeline Low Dose", "Xanomeline High Dose")) {
  ns <- shiny::NS(id)
  shiny::tagList(
    shiny::selectInput(
      inputId = ns("arm"),
      label = "Treatment Arm:",
      choices = arms,
      selected = "All"
    ),
    shiny::textOutput(outputId = ns("summary_text"))
  )
}

arm_filter_server <- function(id, data = pharmaverseadam::adsl) {
  shiny::moduleServer(id, function(input, output, session) {
    resolved_data <- shiny::reactive({
      if (shiny::is.reactive(data)) {
        data()
      } else {
        data
      }
    })

    summary_res <- shiny::reactive({
      selected_arm <- if (is.null(input$arm)) "All" else input$arm
      summarize_safety_arm(resolved_data(), arm = selected_arm)
    })

    output$summary_text <- shiny::renderText({
      res <- summary_res()
      sprintf(
        "%s: %d of %d subjects (safety population)",
        res$arm,
        res$n_arm,
        res$n_total
      )
    })

    shiny::reactive(summary_res())
  })
}

To test arm_filter_server without launching a browser, call shiny::testServer(). Its signature is:

testServer(app = NULL, expr, args = list(), session = MockShinySession$new())

Inside expr, testServer() evaluates expressions using rlang::eval_tidy() with a data mask over the server environment. This gives direct access to:

  • session$setInputs(...) to simulate user inputs and trigger reactive flushes.
  • Server reactives and variables by name (e.g. summary_res()).
  • Rendered outputs via output$<name> (e.g. output$summary_text).
  • Module return values via session$returned and session$getReturned().
shiny::testServer(arm_filter_server, args = list(data = adsl), {
  # Default input state: "All"
  session$setInputs(arm = "All")
  testthat::expect_equal(summary_res()$n_arm, 254L)
  testthat::expect_equal(summary_res()$n_total, 254L)
  testthat::expect_equal(
    output$summary_text,
    "All: 254 of 254 subjects (safety population)"
  )

  # Change input to Placebo
  session$setInputs(arm = "Placebo")
  testthat::expect_equal(summary_res()$n_arm, 86L)
  testthat::expect_equal(
    output$summary_text,
    "Placebo: 86 of 254 subjects (safety population)"
  )

  # Change input to Xanomeline High Dose
  session$setInputs(arm = "Xanomeline High Dose")
  testthat::expect_equal(summary_res()$n_arm, 72L)
  testthat::expect_equal(
    output$summary_text,
    "Xanomeline High Dose: 72 of 254 subjects (safety population)"
  )
})

session$setInputs() updates the mock session’s inputs and automatically triggers an internal reactive flush, allowing synchronous assertions right after each input change.

3 · Module return values: session return bindings and getReturned()

Modules often return reactives to parent callers. In shiny::MockShinySession, two mechanisms expose the return value:

  1. session$returned: A public field on the mock session.
  2. session$getReturned(): An accessor method returning self$returned.

Both point to the same object (identical(session$returned, session$getReturned()) is TRUE).

What session$returned holds matches what the module returns:

  • If the module returns a reactive expression (like shiny::reactive(summary_res())), session$returned holds that reactive function. Call it with parentheses: session$returned() or session$getReturned()().
  • If the module returns a static value, session$returned holds it directly.
  • If the module returns a list of reactives, access each as session$returned$counts() or session$getReturned()$counts().
shiny::testServer(arm_filter_server, args = list(data = adsl), {
  session$setInputs(arm = "Placebo")

  # session$returned holds the reactive expression returned by moduleServer
  testthat::expect_true(shiny::is.reactive(session$returned))

  # Evaluate the returned reactive function
  res <- session$returned()
  testthat::expect_equal(res$n_arm, 86L)
  testthat::expect_equal(res$n_total, 254L)

  # session$getReturned() returns the exact same object
  testthat::expect_identical(session$returned, session$getReturned())
  testthat::expect_equal(session$getReturned()()$n_arm, 86L)
})

4 · Whole-app servers and reactive flushes

testServer() also tests whole-application server functions (server <- function(input, output, session)). When testing an app server that embeds modules, inputs within modules use hyphenated namespace IDs:

app_server <- function(input, output, session) {
  arm_data <- arm_filter_server("filter_sub", data = pharmaverseadam::adsl)

  total_selected <- shiny::reactive({
    arm_data()$n_arm
  })

  output$status <- shiny::renderText({
    sprintf("Selected %d participants", total_selected())
  })
}

shiny::testServer(app_server, {
  session$setInputs(`filter_sub-arm` = "Placebo")
  testthat::expect_equal(total_selected(), 86L)
  testthat::expect_equal(output$status, "Selected 86 participants")

  session$setInputs(`filter_sub-arm` = "Xanomeline Low Dose")
  testthat::expect_equal(total_selected(), 96L)
  testthat::expect_equal(output$status, "Selected 96 participants")
})

While session$setInputs() flushes dependencies automatically, reactive state can also change outside setInputs()—for example, when a module receives a shared shiny::reactiveVal() or an external data feed. In those cases, calling session$flushReact() triggers the flush cycle on demand:

shared_flag <- shiny::reactiveVal(FALSE)

monitor_server <- function(id, flag = shared_flag) {
  shiny::moduleServer(id, function(input, output, session) {
    status <- shiny::reactiveVal("idle")
    shiny::observe({
      if (flag()) {
        status("active")
      } else {
        status("idle")
      }
    })
    shiny::reactive(status())
  })
}

shiny::testServer(monitor_server, args = list(flag = shared_flag), {
  testthat::expect_equal(session$returned(), "idle")

  # Mutate external reactive value directly
  shared_flag(TRUE)

  # Before flush: observer has not executed yet
  testthat::expect_equal(session$returned(), "idle")

  # Explicitly flush the reactive domain
  session$flushReact()
  testthat::expect_equal(session$returned(), "active")
})

5 · What testServer() cannot test

testServer() executes inside a simulated headless session with shiny::MockShinySession. Its boundaries are clear:

  • No browser DOM: HTML is not parsed, laid out, or rendered. testServer() cannot test CSS layout, responsive breakpoints, font rendering, or whether an element is visually hidden.
  • No JavaScript execution: Custom JavaScript bindings (Shiny.addCustomMessageHandler, Shiny.setInputValue from client scripts, jQuery handlers, and HTML widgets) do not run.
  • No client-server network interaction: Websocket reconnections, file uploads through browser dialogs, and latency effects cannot be tested with testServer().

For full browser rendering, client-side JavaScript, and visual regression checks, we use end-to-end browser testing with {shinytest2}, which is covered in a subsequent post.

6 · Tests as evidence: the GxP pharma angle

In clinical trial reporting, interactive Shiny dashboards are increasingly deployed for safety monitoring, cohort filtering, and protocol deviation tracking.

Under GxP validation expectations, manual ad-hoc clicking does not constitute verifiable evidence. Automated tests provide:

  • Automated execution: Running on every pull request via continuous integration.
  • Traceable requirements: A test’s description can name the requirement it checks (for example “safety population = subjects with SAFFL == "Y"”), and the test computes the expected value from that rule, not from a copied number.
  • Regression protection: Refactoring UI styles or layout cannot inadvertently alter underlying clinical counts without tripping test failures.

Continuous integration keeps the test results with the commit, which a later post in the series turns into evidence.

Pitfalls

  • Burying business logic in reactives: Writing complex data wrangling inside shiny::reactive() makes testing cumbersome. Move domain calculations into pure helper functions and test them with testthat::expect_equal() before testing the module.
  • Confusing module return invocation: If your module returns shiny::reactive(...), calling session$returned returns the reactive function, not its evaluated value. Call session$returned() or session$getReturned()().
  • Expecting JavaScript to run in testServer(): If your module depends on a custom JavaScript input handler, testServer() will not invoke it. Pass simulated input values explicitly using session$setInputs().
  • Forgetting flushReact() with external reactive updates: If your test updates an external reactiveVal or reactive source outside session$setInputs(), call session$flushReact() to trigger pending observers.

Companion code

View module-demo.R · Download

Defines a pure clinical filtering helper, a Shiny module (UI and server), and a verification runner exercising server logic against pharmaverseadam::adsl using shiny::testServer(). Requires {shiny} and {pharmaverseadam}. The script’s functions have tests that check the counts against the data and catch a planted bug.

# Testing Shiny server logic with testServer(): defines a pure helper function
# for safety population filtering and arm counts on ADSL, a Shiny module
# (UI + server) for interactive filtering, and an automated verification runner
# using shiny::testServer().
#
#   Rscript module-demo.R

#' Filter safety population and summarize treatment arm counts
#'
#' Filters an ADSL data frame to the safety population (SAFFL == "Y") and
#' optionally to a specific treatment arm (TRT01A), computing participant counts.
#'
#' @param data An ADSL data frame containing `SAFFL` and `TRT01A`.
#' @param arm Treatment arm name to filter by, or "All" for all arms.
#' @return A list with `data` (filtered data frame), `n_arm` (subject count in
#'   selected arm), `n_total` (total subjects in safety population), and
#'   `arm` (the selected arm).
#' @export
summarize_safety_arm <- function(data, arm = "All") {
  if (!is.data.frame(data)) {
    stop("`data` must be a data frame.", call. = FALSE)
  }
  if (!all(c("SAFFL", "TRT01A") %in% names(data))) {
    stop("`data` must contain `SAFFL` and `TRT01A` columns.", call. = FALSE)
  }

  saffl_data <- data[!is.na(data$SAFFL) & data$SAFFL == "Y", , drop = FALSE]
  n_total <- nrow(saffl_data)

  if (identical(arm, "All")) {
    filtered <- saffl_data
  } else {
    filtered <- saffl_data[
      !is.na(saffl_data$TRT01A) & saffl_data$TRT01A == arm,
      ,
      drop = FALSE
    ]
  }

  list(
    data = filtered,
    n_arm = nrow(filtered),
    n_total = n_total,
    arm = arm
  )
}

#' UI for treatment arm filter module
#'
#' @param id Module namespace id.
#' @param arms Character vector of available treatment arms.
#' @return A shiny tagList containing input controls and text output.
#' @export
arm_filter_ui <- function(
  id,
  arms = c("All", "Placebo", "Xanomeline Low Dose", "Xanomeline High Dose")
) {
  ns <- shiny::NS(id)
  shiny::tagList(
    shiny::selectInput(
      inputId = ns("arm"),
      label = "Treatment Arm:",
      choices = arms,
      selected = "All"
    ),
    shiny::textOutput(outputId = ns("summary_text"))
  )
}

#' Server logic for treatment arm filter module
#'
#' @param id Module namespace id.
#' @param data ADSL data frame or a reactive expression returning one.
#' @return A reactive expression returning the summary list from
#'   `summarize_safety_arm()`.
#' @export
arm_filter_server <- function(id, data = pharmaverseadam::adsl) {
  shiny::moduleServer(id, function(input, output, session) {
    resolved_data <- shiny::reactive({
      if (shiny::is.reactive(data)) {
        data()
      } else {
        data
      }
    })

    summary_res <- shiny::reactive({
      selected_arm <- if (is.null(input$arm)) "All" else input$arm
      summarize_safety_arm(resolved_data(), arm = selected_arm)
    })

    output$summary_text <- shiny::renderText({
      res <- summary_res()
      sprintf(
        "%s: %d of %d subjects (safety population)",
        res$arm,
        res$n_arm,
        res$n_total
      )
    })

    shiny::reactive(summary_res())
  })
}

#' Run headless reactive checks on arm_filter_server using testServer
#'
#' @param data ADSL dataset to test against.
#' @return A list containing verified summary counts and status.
#' @export
run_module_checks <- function(data = pharmaverseadam::adsl) {
  saffl_sub <- data[!is.na(data$SAFFL) & data$SAFFL == "Y", , drop = FALSE]
  exp_total <- nrow(saffl_sub)
  exp_pbo <- sum(saffl_sub$TRT01A == "Placebo", na.rm = TRUE)
  exp_low <- sum(saffl_sub$TRT01A == "Xanomeline Low Dose", na.rm = TRUE)
  exp_high <- sum(saffl_sub$TRT01A == "Xanomeline High Dose", na.rm = TRUE)

  results <- list()
  shiny::testServer(arm_filter_server, args = list(data = data), {
    session$setInputs(arm = "All")
    stopifnot(identical(summary_res()$n_arm, exp_total))
    stopifnot(identical(summary_res()$n_total, exp_total))
    stopifnot(identical(session$returned()$n_arm, exp_total))
    stopifnot(identical(session$returned(), session$getReturned()()))

    session$setInputs(arm = "Placebo")
    stopifnot(identical(summary_res()$n_arm, exp_pbo))
    stopifnot(identical(session$returned()$n_arm, exp_pbo))
    pbo_text_out <- output$summary_text

    session$setInputs(arm = "Xanomeline Low Dose")
    stopifnot(identical(summary_res()$n_arm, exp_low))

    session$setInputs(arm = "Xanomeline High Dose")
    stopifnot(identical(summary_res()$n_arm, exp_high))

    results <<- list(
      n_total = exp_total,
      pbo_count = exp_pbo,
      low_count = exp_low,
      high_count = exp_high,
      pbo_text = pbo_text_out,
      passed = TRUE
    )
  })
  results
}

# Run only when called as a script (not when sourced by tests).
if (sys.nframe() == 0L) {
  cat("Running testServer verification on arm_filter_server...\n")
  res <- run_module_checks()
  cat(sprintf("Total safety population: %d\n", res$n_total))
  cat(sprintf("Placebo count:           %d\n", res$pbo_count))
  cat(sprintf("Xanomeline Low Dose:     %d\n", res$low_count))
  cat(sprintf("Xanomeline High Dose:    %d\n", res$high_count))
  cat(sprintf("Placebo output text:     %s\n", res$pbo_text))
  cat("All reactive tests passed via testServer().\n")
}

Sources

Package documentation

Web-repo comparison

NoteUpdates
  • 2026-09-27: Added a Sources section.
  • 2026-09-27: Added a Companion code section with the full script.
  • 2026-09-27: Noted that shared functions match the companion script under automated tests.