Chapter 21. Testing

For simple apps, it’s easy enough to remember how the app is supposed to work so that when you make changes to add new features, you don’t accidentally break existing capabilities. However, as your app gets more complicated, it becomes impossible to hold it all in your head simultaneously. Testing is a way to capture desired behavior of your code in such a way that you can automatically verify that it keeps working the way you expect. Turning your existing informal tests into code is painful when you first do it, because you need to carefully turn every key press and mouse click into a line of code, but once done, it’s tremendously faster to rerun your tests.

We’ll perform automated testing with the testthat package. testthat requires turning your app into a package, but as discussed in Chapter 20, this is not too much work, and I think it pays off for other reasons.

A testthat test looks like this:

test_that("as.vector() strips names", {
  x <- c(a = 1, b = 2)
  expect_equal(as.vector(x), c(1, 2))
})

We’ll come back to the details very soon, but note that a test starts by declaring the intent (“as.vector() strips names”), then uses regular R code to generate some test data. The test data is then compared to the expected result using an expectation, a function that starts with expect_. The first argument is some code to run, and the second argument describes the expected result: here we verify that the output of as.vector(x) equals c(1, 2).

We’ll work through four ...

Get Mastering Shiny now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.