devtools::test()18 System tests
This chapter covers using shinytest2 and testthat to perform system tests on the features and scenarios in your app-package.
βFailure to allow enough time for system test, in particular, is peculiarly disastrous. Since the delay comes at the end of the schedule, no one is aware of schedule trouble until almost the delivery date. Bad news, late and without warning, is unsettling to customers and to managers.β - βThe Mythical Man-Monthβ, Frederick P. Brooks Jr.
System (or end-to-end) tests simulate real user interactions in a βpre-productionβ environment to verify the whole application (or system) works.1 Approaches to system testing vary, but in general, weβll want to run a system test for each feature in our application before a release.
If weβve been documenting our unit and integration tests with BDD feature and scenario descriptions, the system tests can be used to confirm the functional requirements for the primary execution path (or user experience) before release.
18.1 Current tests
Launch app with the shinypak package:
launch('17_test-modules')The current files in our tests folder are below:
tests
βββ testthat
β βββ _snaps
β β βββ text_logo.md
β βββ fixtures
β β βββ make-tidy_ggp2_movies.R
β β βββ tidy_ggp2_movies.rds
β βββ helper.R
β βββ test-mod_scatter_display_server.R
β βββ test-mod_var_input_server.R
β βββ test-scatter_plot.R
β βββ test-text_logo.R
βββ testthat.R
4 directories, 9 filesThe output from devtools::test() is below:
β | F W S OK | Context
β | 0 | mod_scatter_display_server
TEST: START [2025-02-12 07:47:04] COLLECT = collected module values
TEST: END [2025-02-12 07:47:04] COLLECT = collected module values
TEST: START [2025-02-12 07:47:04] OUTPUT = is list
β | 2 | mod_scatter_display_server
TEST: END [2025-02-12 07:47:04] OUTPUT = is list
TEST: START [2025-02-12 07:47:04] OUTPUT = names
TEST: END [2025-02-12 07:47:04] OUTPUT = names
TEST: START [2025-02-12 07:47:04] OUTPUT = Plot object
β Έ | 4 | mod_scatter_display_server
TEST: END [2025-02-12 07:47:04] OUTPUT = Plot object
TEST: START [2025-02-12 07:47:04] OUTPUT = is ggplot
TEST: END [2025-02-12 07:47:04] OUTPUT = is ggplot
β | 5 | mod_scatter_display_server
β | 0 | mod_var_input_server
TEST: START [2025-02-12 07:47:05] RETURNED = test_vals vs. session$returned()
TEST: END [2025-02-12 07:47:05] RETURNED = test_vals vs. session$returned()
β | 1 | mod_var_input_server
β | 0 | scatter_plot
TEST: START [2025-02-12 07:47:05] Step1 = loading movies data
TEST: END [2025-02-12 07:47:05] Step1 = movies data loaded successfully
TEST: START [2025-02-12 07:47:05] Step2 = creating graph
TEST: END [2025-02-12 07:47:05] Step2 = graph created
β | 1 | scatter_plot
β | 0 | text_logo
TEST: START [2025-02-12 07:47:05] snap = text_logo()
TEST: END [2025-02-12 07:47:05] snap = text_logo()
TEST: START [2025-02-12 07:47:05] snap = text_logo('})')
β | 2 | text_logo
TEST: START [2025-02-12 07:47:05] snap = text_logo('h1')
TEST: START [2025-02-12 07:47:05] snap = text_logo('invalid')
TEST: END [2025-02-12 07:47:05] snap = text_logo('invalid')
β | 3 | text_logo
ββ Results ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Duration: 1.8 s
[ FAIL 0 | WARN 0 | SKIP 0 | PASS 10 ]
Nice code.18.2 Setting up shinytest2
shinytest2 requires a few steps to get up and running (most notably the chromote package), but youβll find excellent documentation on the package website.2
shinytest2 (version 0.6.0 and later) requires R 4.1 or higher. When we run shinytest2::use_shinytest2() in an app-package, it detects the package and performs the following setup steps:
β Adding
*_.new.pngto.gitignoreβ Adding
_\\.new\\.png$to.Rbuildignoreβ Adding
shinytest2toSuggestsfield inDESCRIPTION
Earlier versions of shinytest2 also created a tests/testthat/setup-shinytest2.R file with a call to load_app_env(). This function has been superseded, and use_shinytest2() no longer creates the setup file. Instead, weβre told to load app support files inside our tests:
βΉ To load app support files, use `shinytest2::with_app_support()` or
`shinytest2::local_app_support()` within your tests.Our app-package doesnβt need either function, because weβll pass the launch_app() function directly to our tests (see Section 18.4).
We also get some advice on using shinytest2 functions in our code:
β’ In your package code, use `rlang::is_installed("shinytest2")` or
`rlang::check_installed("shinytest2")` to test if shinytest2 is installed
β’ Then directly refer to functions with `shinytest2::fun()`After setting up shinytest2, be sure you can create a new chromote session like the one below:
library(chromote)
b <- ChromoteSession$new()
b$view()If you run into problems running shinytest2 tests, you can upgrade chromium (if youβre on Mac using homebrew):
brew install --cask chromium18.3 Record a test
If we launch the test recorder with shinytest2::record_test(), change the inputs in our application, click on Expect Shiny values and Save test and exit, a test is recorded to a new test file: tests/testthat/test-shinytest2.R
The test runs and saves the PNG snapshot and test values to the tests/testthat/_snaps/ folder:
Loading required package: shiny
[ FAIL 0 | WARN 2 | SKIP 0 | PASS 1 ]
ββ Warning (test-shinytest2.R:10:3): {shinytest2} recording: sap-feature-01 ββββββββ
Adding new file snapshot: 'tests/testthat/_snaps/sap-feature-01-001_.png'
ββ Warning (test-shinytest2.R:10:3): {shinytest2} recording: sap-feature-01 ββββββββ
Adding new file snapshot: 'tests/testthat/_snaps/sap-feature-01-001.json'
[ FAIL 0 | WARN 2 | SKIP 0 | PASS 1 ]If we view the contents test-shinytest2.R we find each action we performed in the test recorder has a corresponding call in the test:
library(shinytest2)
test_that("{shinytest2} recording: sap-feature-01", {
app <- AppDriver$new(name = "sap-feature-01", height = 887, width = 1241)
app$set_inputs(`vars-y` = "imdb_num_votes")
app$set_inputs(`vars-x` = "critics_score")
app$set_inputs(`vars-z` = "genre")
app$set_inputs(`aes-alpha` = 0.7)
app$set_inputs(`aes-size` = 3)
app$set_inputs(`aes-plot_title` = "New plot title")
app$expect_values()
})- 1
-
Initialize the
AppDriver$new()with the name of the test and the dimensions of the Chromium browser.
- 2
-
Change the y axis (
vars-y) to βIMBD number of votesβ (imdb_num_votes)
- 3
-
Change the x axis (
vars-x) to βCritics Scoreβ (critics_score)
- 4
-
Change the color by (
vars-z) to βGenreβ (genre)
- 5
-
Change the point opacity (
aes-alpha) to β0.7β
- 6
-
Change the point size (
aes-alpha) to β3β
- 7
-
Change the plot title to (
aes-plot_title) to βNew plot titleβ - 8
- Export the test values
Weβll use this initial test as a template for writing the steps in our test Scenarios.
The recorded test calls AppDriver$new() without an application, so shinytest2 looks for an app.R file in the package root. This works when we run tests with devtools::test(), but the tests in an installed package (like the ones run by R CMD check and covr) donβt have access to app.R. In the tests below, I pass the launch_app function (without parentheses) as the first argument to AppDriver$new(). shinytest2 recognizes launch_app is a function from our package, so it calls pkgload::load_all() in the background R process when weβre developing, and uses the installed package when the tests run with R CMD check or covr.
18.4 shinytest2 and BDD
There are multiple ways to approach your test layout with testthatβs describe(), it() and/or test_that() functions. Below is an example with dedicated Feature and Scenario descriptions, and a reference to the feature number in an it() call:
describe("Feature 1: Scatter plot data visualization dropdowns
As a film data analyst
I want to explore variables in the movie review data
So that I can analyze relationships between movie reivew sources", {
describe("Scenario: Change dropdown values for plotting
Given the movie review application is loaded
When I choose the variable [ ] for the x-axis
And I choose the variable [ ] for the y-axis
And I choose the variable [ ] for the color
And I choose the size of the points to be [ ]
And I choose the opacity of the points to be [ ]
And I enter '[ ]' for the plot title
Then the scatter plot should show [ ] on the x-axis
And the scatter plot should show [ ] on the y-axis
And the points on the scatter plot should be colored by [ ]
And the size of the points on the scatter plot should be [ ]
And the opacity of the points on the scatter plot should be [ ]
And the title of the plot should be '[ ]'", {
it("Feature 01", {
app <- AppDriver$new(launch_app, name = "feature-01",
height = 800, width = 1173)
app$set_inputs(`vars-y` = "imdb_num_votes")
app$set_inputs(`vars-x` = "critics_score")
app$set_inputs(`vars-z` = "genre")
app$set_inputs(`aes-alpha` = 0.7)
app$set_inputs(`aes-size` = 3)
app$set_inputs(`aes-plot_title` = "New plot title")
app$expect_values()
})
})
})With this approach, you can create the test file as soon as you have a Feature description (and come back later to fill in the Scenarios and tests).
An alternative approach is to use nested describe() functions with each Then step in the it() call (these are what will actually be tested):
library(shinytest2)
describe("Feature 1: Scatter plot data visualization dropdowns
As a film data analyst
I want to explore variables in the movie review data
So that I can analyze relationships between movie review sources", {
describe("Scenario A: Change dropdown values for plotting
Given the movie review application is loaded
When I choose the variable [ ] for the x-axis
And I choose the variable [ ] for the y-axis
And I choose the variable [ ] for the color", {
it("Then the scatter plot should show [ ] on the x-axis
And the scatter plot should show [ ] on the y-axis
And the points on the scatter plot should be colored by [ ]", {
app <- AppDriver$new(launch_app, name = "feature-01-scenario-a",
height = 800, width = 1173)
app$set_inputs(`vars-y` = "imdb_num_votes")
app$set_inputs(`vars-x` = "critics_score")
app$set_inputs(`vars-z` = "genre")
app$expect_values()
})
})
describe("Scenario B: Change dropdown values for plotting
Given the movie review application is loaded
When I choose the size of the points to be [ ]
And I choose the opacity of the points to be [ ]
And I enter '[ ]' for the plot title", {
it("Then the size of the points on the scatter plot should be [ ]
And the opacity of the points on the scatter plot should be [ ]
And the title of the plot should be '[ ]'", {
app <- AppDriver$new(launch_app, name = "feature-01-scenario-b",
height = 800, width = 1173)
app$set_inputs(`aes-alpha` = 0.7)
app$set_inputs(`aes-size` = 3)
app$set_inputs(`aes-plot_title` = "New plot title")
app$expect_values()
})
})
})- 1
-
Test for scenario A
- 2
- Test for scenario B
An important note with this approach is the different names for each AppDriver$new() (otherwise weβd be overwriting the previous snapshot/values).
18.4.1 Testing multiple apps
If we want to test a feature for one of our alternative applications in the inst/ folder, we can use system.file() to pass their location to the app_dir argument of AppDriver$new().
In the test below, the scenario describes changing inputs for x, y, and color:
library(shinytest2)
describe(
"Feature 1: Scatter plot data visualization dropdowns
As a film data analyst
I want to explore movie review variables
So that I can analyze relationships between movie attributes and ratings", {
describe(
"Scenario: Change dropdown values for plotting
Given the movie review application is loaded
When I choose the variable ['Critics Score'] for the x-axis
And I choose the variable ['IMDB number of votes'] for the y-axis
And I choose the variable ['Genre'] for the color", code = {
it("Then the scatter plot should show ['Critics Score'] on the x-axis
And the scatter plot should show ['IMDB number of votes'] on the y-axis
And the points on the scatter plot should be colored by ['Genre']", {
test_logger(start = 'prod-feat-01', msg = "update x, y, and z")
app <- AppDriver$new(system.file("prod/app", package = "sap"),
name = "prod-feat-01",
wait = FALSE, timeout = 3000,
height = 800, width = 1173)
app$set_inputs(`vars-y` = "imdb_num_votes")
app$set_inputs(`vars-x` = "critics_score")
app$set_inputs(`vars-z` = "genre")
app$set_inputs(`aes-alpha` = 0.7)
app$set_inputs(`aes-size` = 3)
app$set_inputs(`aes-plot_title` = "New plot title")
app$expect_values()
test_logger(end = 'prod-feat-01', msg = "update x, y, and z")
})
})
})- 1
-
Use
system.file()to access application ininst/tidy-data
- 2
-
Adjust the
waitandtimeoutso the test will run
As of version 0.6.0, AppDriver$new() only calls pkgload::load_all() for packages in development. When we run devtools::test(), sap is in development, so system.file() points to the inst/ folder in our source code. When the tests run against the installed package (i.e., with R CMD check or covr), the app runs from the installed copy of sap.
Note that Iβve changed the wait and timeout arguments in AppDriver$new() because this tests takes over 10 seconds to complete (which I can see with my test_logger() output). When I confirm this in the output png file, I can see the x, y, and color values have been changed (and the missing values have been removed).
18.4.2 The app process
shinytest2 0.6.0 added AppDriver$get_process(), which returns the background R process running our app (a callr::r_process object). We can use it to confirm the app is running, and that app$stop() shuts it down:
test_that("app process starts and stops", {
app <- AppDriver$new(launch_app, name = "process")
proc <- app$get_process()
expect_true(proc$is_alive())
app$stop()
expect_false(proc$is_alive())
})- 1
-
Background R process that runs
launch_app() - 2
- The app is running
- 3
-
app$stop()ends the process
None of the apps in sap call shiny::stopApp(), but if an app exits on its own (for example, from a βQuitβ button), we can call app$get_process()$wait() to wait for the process to finish before calling app$stop().
18.5 The test.mode option
Weβve included an argument in both of the standalone app functions to allow for options to be passed to shinyApp():
launch_app(options = list())If weβre testing our application, we can include the test.mode = TRUE option, which will return any values passed to exportTestValues():
launch_app(options = list(test.mode = TRUE), run = 'p')We can also include this in our .Rprofile as:3
options(shiny.testmode = TRUE)18.6 Exporting test values
To export values, place the name of exported reactive values in curly brackets ({}). Below is an example using the inputs() reactive object in the mod_scatter_display_server():
exportTestValues(
x = { inputs()$x },
y = { inputs()$y },
z = { inputs()$z },
alpha = { inputs()$alpha },
size = { inputs()$size },
title = { inputs()$plot_title }
)In our test, we can create the AppDriver$new() object, extract the values with get_values():
app <- AppDriver$new(launch_app, name = "test-values",
height = 800, width = 1173,
wait = FALSE, timeout = 300000)
test_values <- app$get_values()
test_values[['export']]$`plot-alpha`
[1] 0.5
$`plot-size`
[1] 2
$`plot-title`
[1] ""
$`plot-x`
[1] "imdb_rating"
$`plot-y`
[1] "audience_score"
$`plot-z`
[1] "mpaa_rating"Now we can write tests against any of the exported values:
expect_equal(object = test_values[['export']]$`plot-alpha`, expected = 0.5)
expect_equal(object = test_values[['export']]$`plot-size`, expected = 2)
expect_equal(object = test_values[['export']]$`plot-title`, expected = "")
expect_equal(object = test_values[['export']]$`plot-x`, expected = "imdb_rating")
expect_equal(object = test_values[['export']]$`plot-y`, expected = "audience_score")
expect_equal(object = test_values[['export']]$`plot-z`, expected = "mpaa_rating")18.7 Test failures
In Positron
, the Testing menu item gives us a display of the test files and individual tests.
When a test fails, weβre alerted of the failure and the specific test the output didnβt meet the expectation:
In this case, we can see itβs just a typo in the expected output. After making the change, we can re-run the tests and view the output in the TEST RESULTS:
TEST RESULTS also keeps a record of the previous test runs for us to review.
18.8 Test _snaps/
After writing our system tests and running devtools::test(), the tests/testthat/_snaps/ folder contains the follow folders and files:
tests/testthat/_snaps/
βββ shinytest2
β βββ feature-01-scenario-a-001.json
β βββ feature-01-scenario-a-001_.png
β βββ feature-01-senario-b-001.json
β βββ feature-01-senario-b-001_.png
βββ shinytest2-prod
β βββ prod-feat-01-001.json
β βββ prod-feat-01-001_.png
βββ text_logo.md
3 directories, 7 filesThese outputs correspond to the test files that create snapshots in the tests/testthat/ folder:
tests/testthat/
βββ test-shinytest2-export.R
βββ test-shinytest2-prod.R
βββ test-shinytest2.R18.9 System test coverage
Before version 4.0.0 of covr, the code exercised by our shinytest2 tests didnβt count toward our packageβs test coverage (the app runs in a separate R process). covr::package_coverage() now includes the app code run by shinytest2 tests, so we can see how much of our application our system tests reach.
AppDriver$new() skips tests on CRAN, and covr doesnβt set the NOT_CRAN environment variable, so we need to set it before checking coverage:
Sys.setenv(NOT_CRAN = "true")
covr::package_coverage()sap Coverage: 79.74%
R/display_type.R: 0.00%
R/log_message.R: 0.00%
R/testthat.R: 53.85%
R/launch_app.R: 64.29%
R/logr_msg.R: 65.00%
R/movies_server.R: 68.42%
R/mod_aes_input.R: 89.19%
R/movies_ui.R: 96.77%
R/mod_scatter_display.R: 100.00%
R/mod_var_input.R: 100.00%
R/scatter_plot.R: 100.00%
R/text_logo.R: 100.00%Without the system tests, the coverage for sap is 25.08%, and launch_app.R, movies_ui.R, movies_server.R, and mod_aes_input.R are all at 0%. The system tests are the only tests that run the full application, so they cover the code our unit and module tests canβt reach.
Launch app with the shinypak package:
launch('18_tests-system')Recap
Adopting a behavior-driven development approach in system testing can help to fill the gulf between non-technical stakeholders and developers by encouraging natural, descriptive language. Using complete sentences to describe to define and communicate the application requirements will make it easier for anyone to catch unexpected behaviors.
Using βFeaturesβ (As a , I want, So that) and βScenariosβ (Given, When, Then) make system tests clear (and easier to update if the specifications change).
System tests should strive to replicate the production conditions, even when/if itβs not possible to perfectly replicate the environment.β©οΈ
A great place to start is the Getting Started vignette.β©οΈ
We covered the
.Rprofilein Section 4.7.3.β©οΈ






