# install.packages('pak')
::pak('mjfrigaard/shinypak') pak
13 Testing modules
In the previous chapters we covered adding test fixtures and helpers to our test suite. In this chapter, we’re going briefly discuss some tips for testing modules with testServer()
–specifically, how to verify modules are transferring values correctly.
13.1 Integration tests
Integration tests verify that functions and components work together, and often involves instantiating multiple objects to interact with each other in a single test.
Launch app with the shinypak
package:
launch('13_tests-modules')
We can combine the BDD functions with testServer()
to test reactive interactions between modules. For example, to confirm that the drop-down feature requirement is working (i.e., that user-inputs are updating in the application), we need to test two changes:
- Values passed to the UI are returned from
mod_var_input_server()
- The reactive values returned from
mod_var_input_server()
are passed intomod_scatter_display_server()
and available as the reactive objectinputs()
The feature, background, and scenario for the changes in mod_var_input_server()
are provided below:
describe(
"Feature: Scatter Plot Configuration in Movie Review Application
As a user
I want the initial graph pre-configured with variables and aesthetics,
So that I can change the inputs and see a meaningful visualization.",
code = {
describe(
"Background: Initial scatter plot x, y, color values
Given the movie review application is loaded
And the scatter plot initial x-axis value is [IMDB Rating]
And the scatter plot initial y-axis value is [Audience Score]
And the scatter plot initial color value is [MPAA Rating]
And the initial opacity of the points is set to [0.5]
And the initial size of the points is set to [2]
And the initial plot title is set to [Enter plot title]", code = {
it("Scenario: Changing scatter plot x, y, color values
Given the movie review application is loaded
When I choose the [Critics Score] variable for the x-axis
And I choose the [Runtime] variable for the y-axis
And I choose the [Title type] variable for color
Then the scatter plot should show [Critics score] on the x-axis
And the scatter plot should show [Runtime] on the y-axis
And the points on the scatter plot should be colored by [Title type]
And the opacity of the points should be set to [0.5]
And the size of the points should be set to [2]
And the plot title should be [Enter plot title]", code = {
::testServer(app = mod_var_input_server, expr = {
shiny
# test code -----
})
})
}) })
13.1.1 Testing return values
Inside testServer()
, we can create a list of initial graph inputs for mod_var_input_server()
, then pass identical values to session$setInputs()
, and confirm the returned object with session$returned()
:1
::testServer(app = mod_var_input_server, expr = {
shiny
test_logger(start = "var_inputs", msg = "initial returned()")
# create list of output vals
<- list(y = "imdb_rating",
test_vals x = "audience_score",
z = "mpaa_rating",
alpha = 0.75,
size = 3,
plot_title = "Example title")
# change inputs
$setInputs(y = "imdb_rating",
sessionx = "audience_score",
z = "mpaa_rating",
alpha = 0.75,
size = 3,
plot_title = "Example title")
expect_equal(
object = session$returned(),
expected = test_vals
)
test_logger(end = "var_inputs", msg = "initial returned()")
})
- 1
-
Call to
testServer()
- 2
-
Create output values for comparison
- 3
-
Set each input using
setInputs(input = )
- 4
-
Confirm returned values against
test_vals
The test above confirms the initial values can be passed and returned from mod_var_input_server()
.
13.1.2 Flushing the reactives
If we want to test changing inputs, we should call session$flushReact()
to remove the values set by session$setInputs()
2
::testServer(app = mod_var_input_server, expr = {
shiny# flush reactives
$flushReact()
sessiontest_logger(start = "var_inputs", msg = "updated returned()")
# set inputs
$setInputs(y = "critics_score",
sessionx = "runtime",
z = "title_type",
alpha = 0.5,
size = 2,
plot_title = "Enter plot title")
expect_equal(object = session$returned(),
expected = list(y = "critics_score",
x = "runtime",
z = "title_type",
alpha = 0.5,
size = 2,
plot_title = "Enter plot title"))
test_logger(end = "var_inputs", msg = "updated returned()")
})
- 1
-
Call to
testServer()
- 2
-
Flush reactives from previous
expect_equal()
- 3
-
Set changed input values using
setInputs(input = )
- 4
-
Confirm returned values against
session$returned()
The final result of running test_active_file()
on test-mod_var_input.R
is below:
[ FAIL 0 | WARN 0 | SKIP 0 | PASS 0 ]
INFO [2023-11-08 20:00:39] [ START var_inputs = initial returned()]
[ FAIL 0 | WARN 0 | SKIP 0 | PASS 1 ]
INFO [2023-11-08 20:00:39] [ END var_inputs = initial returned()]
INFO [2023-11-08 20:00:39] [ START var_inputs = updated returned()]
[ FAIL 0 | WARN 0 | SKIP 0 | PASS 2 ] INFO [2023-11-08 20:00:39] [ END var_inputs = updated returned()]
13.1.3 Testing module parameters
Now that we’ve confirmed mod_var_input_server()
is returning the initial updated values, we want to make sure reactive values are passed correctly into mod_scatter_display_server()
.
In movies_server()
, when we pass selected_vars
to the var_inputs
argument, we’re not passing the returned values (this is why we don’t need the parentheses). We’re calling on the method (or function) created by the call to reactive()
(inside mod_var_input_server()
).
I’ve included the movies_server()
function below to refresh our memory of how this should work:3
<- function(input, output, session) {
movies_server
<- mod_var_input_server("vars")
selected_vars
mod_scatter_display_server("plot", var_inputs = selected_vars)
}
- 1
-
Calls
return(reactive(list(...)))
When we pause execution with Posit Workbench’s debugger we can see the difference between calling selected_vars
and selected_vars()
:
1]> selected_vars
Browse[reactive({
list(
y = input$y,
x = input$x,
z = input$z,
alpha = input$alpha,
size = input$size,
plot_title = input$plot_title
) })
1]> selected_vars()
Browse[$y
1] "audience_score"
[
$x
1] "imdb_rating"
[
$z
1] "mpaa_rating"
[
$alpha
1] 0.5
[
$size
1] 2
[
$plot_title
1] "" [
We’ll cover using browser()
and the IDE’s debugger more the debugging chapter.
The feature and scenario for the functionality above is captured in testthat
’s BDD functions below:
describe(
"Feature: Scatter Plot Configuration in Movie Review Application
As a user
I want the initial graph pre-configured with variables and aesthetics,
So that I can immediately see a meaningful visualization.",
code = {
it(
"Scenario: Scatter plot initial x, y, color values
Given the movie review application is loaded
When I view the initial scatter plot
Then the scatter plot should show 'IMDB Rating' on the x-axis
And the scatter plot should show 'Audience Score' on the y-axis
And the points on the scatter plot should be colored by 'MPAA Rating'
And the size of the points should be set to '2'
And the opacity of the points should be set to '0.5'
And the plot title should be 'Enter plot title'",
code = {
}) })
Inside testServer()
, if we’re testing a module function that collects the reactive values, we need to wrap those values in reactive()
in the args()
argument: 4
::testServer(
shinyapp = mod_scatter_display_server,
args = list(
var_inputs =
reactive(
list(
x = "critics_score",
y = "imdb_rating",
z = "mpaa_rating",
alpha = 0.5,
size = 2,
plot_title = "Enter Plot Title"
)
)
),expr = {
test_logger(start = "display", msg = "selected_vars initial values")
expect_equal(
object = inputs(),
expected = list(
x = "critics_score",
y = "imdb_rating",
z = "mpaa_rating",
alpha = 0.5,
size = 2,
plot_title = "Enter Plot Title"
)
)test_logger(end = "display", msg = "selected_vars initial values")
})
- 1
-
List of reactive variable inputs
- 2
-
Compare
inputs()
to initial values
I’ve included the example above because it’s not included on the testServer()
documentation, and I’ve found this method works well if you want to confirm two modules are communicating (i.e., returning and collecting outputs). System test with shinytest2
are a better option if we’re trying to capture a more comprehensive execution path (i.e., user scenario) in the application.
13.2 Module test coverage
When we check the code coverage for the test above, we can see it confirms var_inputs
is communicating the reactive values to inputs()
in mod_scatter_display_server()
, but this test doesn’t execute the call to plotOutput()
:
Ctrl/Cmd + Shift + R
:::test_coverage_active_file() devtools
13.2.1 Testing module outputs
To confirm the plot is being created properly in mod_scatter_display_server()
, we can’t use the ggplot2::is.ggplot()
function because the plot is being rendered by renderPlot()
. However, we can verify the structure of the output$scatterplot
object using any of the following expectations:
expect_true(
object = is.list(output$scatterplot))
expect_equal(
object = names(output$scatterplot),
expected = c("src", "width", "height", "alt", "coordmap"))
expect_equal(
object = output$scatterplot[["alt"]],
expected = "Plot object")
It’s also possible to build the graph inside the test using the same code from the module server function, then confirm it with ggplot2::is.ggplot()
:
<- scatter_plot(movies,
plot x_var = inputs()$x,
y_var = inputs()$y,
col_var = inputs()$z,
alpha_var = inputs()$alpha,
size_var = inputs()$size) +
::labs(
ggplot2title = inputs()$plot_title,
x = stringr::str_replace_all(
::toTitleCase(inputs()$x), "_", " "),
toolsy = stringr::str_replace_all(
::toTitleCase(inputs()$y), "_", " ")) +
tools::theme_minimal() +
ggplot2::theme(legend.position = "bottom")
ggplot2
::expect_true(ggplot2::is.ggplot(plot)) testthat
- 1
-
Build graph (same code from module function)
- 2
-
Confirm
ggplot2
object is built
If we’re still skeptical this test is confirming the plot is being built correctly, we can pass plot
to print()
in the test and the plot will appear in the Plots pane.
Recap
Read more about returned values in the section titled, ‘Modules with return values’ in the Shiny documentation.↩︎
Read more about flushing reactive values in the section titled, ‘Flushing Reactives’ in the Shiny documentation.↩︎
selected_vars
are the reactive plot values returned frommod_var_input_server()
.↩︎Read more about adding parameters to
testServer()
in the section titled, ‘Modules with additional parameters’ in the Shiny documentation.↩︎