R
R packages
Best practices
Testing series · part 3

Snapshot tests for R output, tables and plots

Automate regression testing for complex printed output, clinical tables, and plots

Capture complex console output, rtables layouts, and plots with testthat snapshots and vdiffr to catch regressions without fragile manual assertions.
Published

2026-09-26

Modified

2026-09-27

The problem

In the first post in this series, we wrote unit tests with explicit assertions like expect_equal() and expect_identical(). When a function returns a scalar number, a vector, or a small data frame, writing the expected value by hand is straightforward.

That approach breaks down when the expected output is complex, multi-line, or visual:

  • Formatted console output: Pretty-printed tables, ASCII borders, and indented trees.
  • Diagnostic messages and errors: Informational notices, warnings, and multi-line errors built with {cli}.
  • Complex nested objects: Statistical models or nested lists where hand-writing expected structures requires pages of brittle assertions.
  • Rendered clinical tables: Tabular reports produced by {rtables} with hierarchical column splits, statistics rows, and formatting templates.
  • Graphical plots: Data visualisations produced with {ggplot2} or base graphics, where layout, margins, legends, and alignment matter.

When teams test these with standard equality assertions, they either spend hours writing fragile string checks filled with escaped quotes and newlines, or write shallow assertions that check only the object class, leaving the rendered layout unprotected against regressions.

Snapshot tests (or golden tests) solve this dilemma. Instead of hand-coding expected results in test scripts, you capture reference output in a human-readable file managed by {testthat}. When code changes, testthat compares the new output against the recorded snapshot and highlights differences line by line.

When to use snapshot tests (and when not to)

Snapshot tests are a specialised tool. Use them when:

  1. The output is awkward to write by hand, such as printed console representations, multi-line error diagnostics, or graphical figures.
  2. The primary value lies in human inspection, verifying that a table layout is legible or an error message is helpful.
  3. You need regression protection across large objects where asserting individual elements would require excessive boilerplate.

Do not use snapshot tests for:

  • Simple values: If you expect 2 or "placebo", use expect_equal(). A snapshot adds file management overhead and obscures test intent.
  • Noisy or volatile output: Text containing unseeded random values, timestamps, memory addresses, or temporary file paths will change on every run. Unless you scrub volatile tokens, snapshots generate false failures.
  • Internal implementation details: Snapshot public interfaces and user-facing outputs, not internal data structures that change during routine refactoring.

The web-repo way

In JavaScript and TypeScript repositories, frameworks such as Vitest and Jest make snapshot testing and visual regression a core part of development:

// src/components/summary-card.test.ts
import { describe, it, expect } from "vitest";
import { renderSummaryCard } from "./summary-card";

describe("renderSummaryCard", () => {
  it("renders clinical summary card correctly", () => {
    const card = renderSummaryCard({ studyId: "STUDY-01", enrolled: 120 });
    // Serializes the DOM node to __snapshots__/summary-card.test.ts.snap
    expect(card).toMatchSnapshot();
  });
});

Web repositories rely on three fundamental patterns:

  1. Dedicated snapshot files: Vitest stores serialized representations in separate .snap files alongside tests (or inline via toMatchInlineSnapshot()).
  2. Reviewable diffs in pull requests: When a component’s markup changes, git records the diff in the snapshot file. Reviewers evaluate visual changes directly in the pull request.
  3. Visual regression testing: Tools like Playwright and Storybook capture pixel-by-pixel or vector snapshots of rendered web pages to catch CSS and layout regressions.

The R way

In R packages, {testthat} (3rd edition) and {vdiffr} provide the equivalent toolset for console output, structured data, whole files, and plots.

1 · Console output, messages, and errors: expect_snapshot()

expect_snapshot() evaluates an expression as if it were typed in the console. It captures standard output, printed representations, messages, warnings, and errors:

# tests/testthat/test-format_summary.R

test_that("format_patient_summary() prints formatted console block", {
  expect_snapshot(
    format_patient_summary(id = "SUBJ-001", age = 64, arm = "Placebo")
  )
})

By default, an unexpected error inside expect_snapshot() causes the test to fail. To deliberately test and capture an error message, set error = TRUE:

test_that("validate_subject() rejects invalid identifiers", {
  expect_snapshot(
    validate_subject("INVALID_ID"),
    error = TRUE
  )
})

With error = TRUE, testthat expects at least one expression to signal an error and records the message in the snapshot. If the expression executes without error, the expectation fails.

2 · Serializing structured objects: expect_snapshot_value()

If you care about the return value of an object rather than its printed console representation, use expect_snapshot_value(). It serializes the object using one of four styles set by style:

Style Underlying mechanism Strengths Trade-offs
"json" jsonlite::toJSON() Clean, human-readable JSON Best for lists, vectors, and simple objects
"json2" jsonlite::serializeJSON() Preserves more R types and attributes More verbose JSON syntax
"deparse" base::deparse() Depicts objects as valid R code Can become unwieldy on nested objects
"serialize" base::serialize() (base64) Works for any R object Opaque binary; unreadable in git diffs

For nested parameter lists and summary structures, "json" produces the clearest diff in git:

test_that("compute_demographics() returns expected parameter structure", {
  res <- compute_demographics(study = "STUDY-01")
  expect_snapshot_value(res, style = "json")
})

expect_snapshot_value() also accepts a tolerance argument (default testthat_tolerance(), the same as expect_equal()), so tiny floating-point differences don’t trigger false alarms.

3 · Whole-file snapshots: expect_snapshot_file()

When code generates output files on disk—such as CSV exports, generated reports, or standalone text documents—use expect_snapshot_file():

test_that("export_study_manifest() writes expected CSV output", {
  manifest_path <- withr::local_tempfile(fileext = ".csv")
  export_study_manifest(manifest_path)

  expect_snapshot_file(
    manifest_path,
    name = "study_manifest.csv",
    compare = compare_file_text
  )
})

expect_snapshot_file() stores reference files under tests/testthat/_snaps/<test>/<name>. By default it compares files line by line with compare_file_text() (ignoring Windows versus Unix line endings) only when name ends in .r, .R, .Rmd, .md or .txt; everything else, including .csv and .json, is compared byte by byte with compare_file_binary(). That’s why the example passes compare = compare_file_text for a CSV.

4 · Where snapshots live and how to review them

Snapshots live inside your package under tests/testthat/_snaps/:

  • Standard snapshots for test-demographics.R live in tests/testthat/_snaps/demographics.md.
  • File snapshots created by expect_snapshot_file() live in tests/testthat/_snaps/demographics/<name>.
  • Environmental variants live in subdirectories such as tests/testthat/_snaps/<variant>/demographics.md.

Snapshots are stored in human-readable Markdown:

# format_patient_summary() prints formatted console block

    Code
      format_patient_summary(id = "SUBJ-001", age = 64, arm = "Placebo")
    Output
      Subject: SUBJ-001
      Age:     64
      Arm:     Placebo

Each test starts with a level 1 heading (#), followed by the code and its recorded output indented by four spaces; several snapshots in one test are separated by ---.

Committing snapshots to version control

Snapshot files must be committed to git. They are not ephemeral caches; they represent the recorded specification of your software’s expected output. Committing them ensures that every pull request displays an exact diff whenever output changes.

Reviewing changes locally

When a snapshot fails because output has intentionally changed, testthat provides two tools:

  • testthat::snapshot_review(): opens a small Shiny app that shows each changed snapshot (text diffs, or old and new images) so you can accept or skip it.
  • testthat::snapshot_accept("demographics"): Programmatically accepts changes for a test file, updating _snaps/demographics.md and removing temporary .new.md files.
# Review differences interactively in a Shiny app
testthat::snapshot_review()

# Or accept changes for a specific test file
testthat::snapshot_accept("demographics")

5 · Snapshot lifecycle: first run, changes, CI, and CRAN

Understanding snapshot behaviour across environments prevents unexpected failures:

[Local First Run]    ──> Saves to _snaps/{test}.md    ──> Emits warning ──> Test PASSES
[Local Match]        ──> Compares via waldo::compare()──> No diff       ──> Test PASSES
[Local Mismatch]     ──> Writes _snaps/{test}.new.md  ──> Shows diff    ──> Test FAILS
[CI, new snapshot]   ──> Not recorded                 ──> Error         ──> Test FAILS
[CRAN (cran = FALSE)]──> Not compared                 ──> Returns       ──> Neither pass nor fail
  1. First run locally: When testthat encounters a new snapshot expectation, it writes tests/testthat/_snaps/{test}.md, emits a warning (Adding new snapshot:), and passes the test.
  2. Changed snapshot locally: If code changes and output diverges, testthat displays a waldo diff in the console, writes the new output to _snaps/{test}.new.md, and fails the test.
  3. Continuous Integration (CI): when the CI environment variable is "true" (GitHub Actions sets it), creating a new snapshot fails instead of passing. If a developer writes a snapshot test but forgets to commit its _snaps/ file, the test fails on CI instead of quietly passing.
  4. CRAN checks: Snapshot expectations default to cran = FALSE. When running on CRAN (that is, when NOT_CRAN isn’t "true"), a snapshot expectation just returns: it neither succeeds nor fails, and the rest of the test still runs. This prevents minor upstream formatting shifts or platform font differences from breaking CRAN checks. If you explicitly set cran = TRUE, snapshots are verified on CRAN. With error = TRUE, the expectation fails even on CRAN if the expected error isn’t thrown (or an unexpected one is).

6 · Managing volatile output: transform and variant

Snapshots require deterministic output. When text contains fluctuating elements, two arguments provide control:

Scrubbing text with transform

The transform argument takes a function that accepts a character vector of output lines and returns a scrubbed character vector:

scrub_volatile <- function(lines) {
  # Replace fluctuating timestamps and temporary directories
  lines <- gsub("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}", "<TIMESTAMP>", lines)
  lines <- gsub("/tmp/Rtmp[A-Za-z0-9]+", "<TEMPDIR>", lines)
  lines
}

test_that("export_pipeline() logs deterministic progress", {
  expect_snapshot(
    run_export_pipeline(),
    transform = scrub_volatile
  )
})

By scrubbing dynamic paths and timestamps into fixed tokens (<TIMESTAMP>, <TEMPDIR>), the snapshot remains stable across runs and machines.

Platform differences with variant

When output legitimately differs across operating systems or R versions, use variant:

test_that("numerical summary matches platform representation", {
  os_variant <- if (.Platform$OS.type == "windows") "windows" else "unix"
  expect_snapshot(
    print_complex_summary(),
    variant = os_variant
  )
})

Snapshots are stored in tests/testthat/_snaps/<variant>/<test>.md. Use variants sparingly, and delete a variant’s folder when you stop supporting that environment.

7 · Visual regression for plots with vdiffr

You cannot reliably verify graphical plots by comparing deparsed code. The {vdiffr} package provides visual regression testing by converting plots into deterministic SVG files:

# tests/testthat/test-plots.R

test_that("age by arm plot renders consistently", {
  adsl_saf <- subset(pharmaverseadam::adsl, SAFFL == "Y")
  p <- ggplot2::ggplot(adsl_saf, ggplot2::aes(x = TRT01A, y = AGE)) +
    ggplot2::geom_boxplot() +
    ggplot2::labs(title = "Age by actual treatment", x = NULL, y = "Age (years)")

  vdiffr::expect_doppelganger("age-by-arm", p)
})

vdiffr::expect_doppelganger() takes a title (sanitized to create the SVG file name) and a plot object (a ggplot, a recorded plot, or a function that draws a base plot). It writes the reference SVG to tests/testthat/_snaps/plots/age-by-arm.svg.

If a change alters margins, point sizes, or fonts:

  • The test fails.
  • Under R CMD check, vdiffr logs the failures to tests/vdiffr.Rout.fail.
  • Running testthat::snapshot_review() opens an interactive visual diff viewer to compare the reference SVG against the new rendering.

8 · The pharma angle: clinical tables as regression benchmarks

In clinical reporting, Tables, Figures, and Listings (TFLs) are primary deliverables. Statistical analysis plans define rigorous layout specifications: column headers with treatment counts (N=xx), indented summary labels, and strict decimal formatting templates (such as xx.x (xx.x)).

Building tables with {rtables} and data from {pharmaverseadam} produces complex hierarchical layouts:

library(rtables)

adsl_saf <- subset(pharmaverseadam::adsl, SAFFL == "Y")

lyt <- basic_table() |>
  split_cols_by("TRT01A") |>
  add_colcounts() |>
  analyze("AGE", afun = function(x) {
    in_rows(
      "Mean (SD)" = rcell(c(mean(x), sd(x)), format = "xx.x (xx.x)"),
      "Median" = rcell(median(x), format = "xx.x")
    )
  })

tbl <- build_table(lyt, adsl_saf)

Asserting this table by manually indexing cells or concatenating strings is tedious and fragile. Snapshot testing the rendered table captures the entire formatted layout:

test_that("adsl baseline demographic summary table layout matches snapshot", {
  expect_snapshot(tbl)
})

When evaluated, expect_snapshot(tbl) records the exact ASCII table in _snaps/demographics.md:

             Placebo     Xanomeline High Dose   Xanomeline Low Dose
              (N=86)            (N=72)                (N=96)       
———————————————————————————————————————————————————————————————————
Mean (SD)   75.2 (8.6)        73.8 (7.9)            76.0 (8.1)     
Median         76.0              75.5                  78.0        

In regulated environments, reviewing snapshot diffs in pull requests links testing directly to change control:

  • Auditable change tracking: If an upstream package update changes table padding or an algorithm adjusts rounding, git diffs highlight the exact text rows affected.
  • Verification evidence: Snapshot files provide concrete, human-readable records that output formatting matches study specifications.
  • Risk-based validation: Reviewers inspect the visual impact of code refactors before merging, preventing formatting drift across clinical deliverables.

The next post in this series covers testing Shiny server logic with testServer().

Pitfalls

  • Forgetting to commit _snaps/: New snapshots pass locally on the first run. If you forget to commit the generated markdown or SVG files, CI detects missing reference files and fails the build.
  • Blindly running snapshot_accept(): Snapshot testing works only if humans review the changes. Accepting snapshot changes without inspecting the diff defeats the entire purpose of the test.
  • Snapshotting unseeded or dynamic output: Output containing Sys.time(), random numbers, or process IDs will fail continuously. Always isolate random seeds with withr::local_seed() or scrub strings with transform =.
  • Using snapshots for simple scalar assertions: Snapshotting expect_snapshot(nrow(df)) adds file management overhead without benefit. Use expect_equal() for scalar values.
  • Over-relying on variants: Variants duplicate snapshot files. Keep variants minimal and delete obsolete variant directories when older environments are retired.

Companion code

View snapshot-demo.R · Download

Builds a throwaway package whose tests snapshot a printed table with expect_snapshot() and a plot with vdiffr::expect_doppelganger(), runs them twice (record, then compare), then changes the output so you can see a snapshot fail. Requires {testthat}, {usethis}, {withr}, {ggplot2}, and {vdiffr}.

# Snapshot tests, end to end: builds a throwaway package whose tests snapshot a
# printed summary with expect_snapshot() and a plot with
# vdiffr::expect_doppelganger(). Runs the tests twice (record, then compare),
# then changes the output so a snapshot fails.
#
#   Rscript snapshot-demo.R

demo_files <- list(
  "R/age-summary.R" = c(
    "#' Print a small age summary",
    "#' @export",
    "print_age_summary <- function(age) {",
    "  if (!is.numeric(age)) stop(\"`age` must be numeric.\", call. = FALSE)",
    "  cat(\"n:        \", length(age), \"\\n\", sep = \"\")",
    "  cat(\"Mean (SD):\", sprintf(\"%.1f (%.1f)\", mean(age), stats::sd(age)), \"\\n\")",
    "  invisible(age)",
    "}"
  ),
  "R/age-plot.R" = c(
    "#' Box plot of age by arm",
    "#' @export",
    "age_plot <- function(data) {",
    "  ggplot2::ggplot(data, ggplot2::aes(x = arm, y = age)) +",
    "    ggplot2::geom_boxplot() +",
    "    ggplot2::labs(x = NULL, y = \"Age (years)\")",
    "}"
  ),
  "tests/testthat/test-age-summary.R" = c(
    "test_that(\"print_age_summary() output is stable\", {",
    "  expect_snapshot(print_age_summary(c(64, 71, 80)))",
    "})",
    "",
    "test_that(\"print_age_summary() explains a wrong input\", {",
    "  expect_snapshot(print_age_summary(\"64\"), error = TRUE)",
    "})"
  ),
  "tests/testthat/test-age-plot.R" = c(
    "test_that(\"age_plot() looks the same\", {",
    "  data <- data.frame(arm = rep(c(\"A\", \"B\"), each = 3), age = c(60, 65, 70, 62, 68, 74))",
    "  vdiffr::expect_doppelganger(\"age-plot\", age_plot(data))",
    "})"
  )
)

# Creates the package and returns its path.
make_demo_package <- function(path = file.path(tempdir(), "snapdemo")) {
  usethis::create_package(path, rstudio = FALSE, open = FALSE)
  usethis::with_project(path, {
    usethis::use_testthat(3)
    usethis::use_package("ggplot2")
    usethis::use_package("vdiffr", type = "Suggests")
  })
  for (file in names(demo_files)) {
    writeLines(demo_files[[file]], file.path(path, file))
  }
  path
}

# Runs the package's tests. `ci = FALSE` because this demo records new
# snapshots on purpose: with CI=true, testthat fails a test that would create
# a new snapshot (you forgot to commit it).
run_demo_tests <- function(
  path,
  reporter = testthat::default_reporter(),
  ci = FALSE
) {
  withr::local_envvar(CI = tolower(as.character(ci)))
  testthat::test_local(path, reporter = reporter, stop_on_failure = FALSE)
}

# Changes the printed output: one decimal place becomes two.
change_output <- function(path) {
  file <- file.path(path, "R", "age-summary.R")
  code <- readLines(file)
  writeLines(sub("%.1f (%.1f)", "%.2f (%.2f)", code, fixed = TRUE), file)
}

snapshot_files <- function(path) {
  list.files(file.path(path, "tests", "testthat", "_snaps"), recursive = TRUE)
}

# Run only when called as a script (not when sourced by the tests).
if (sys.nframe() == 0L) {
  path <- make_demo_package()
  message("Run 1: records the snapshots")
  run_demo_tests(path)
  print(snapshot_files(path))
  cat(
    readLines(file.path(path, "tests/testthat/_snaps/age-summary.md")),
    sep = "\n"
  )
  message("Run 2: compares against them")
  run_demo_tests(path)
  message("Run 3: after changing the output")
  change_output(path)
  run_demo_tests(path)
  print(snapshot_files(path)) # the .new.md file holds the changed output
}

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.