-
Notifications
You must be signed in to change notification settings - Fork 2
/
slides.qmd
1804 lines (1174 loc) · 41.3 KB
/
slides.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
#title: "Introduction to Snapshot Testing in R"
format:
revealjs:
css: style.css
theme: simple
slide-number: true
preview-links: auto
code-link: true
footer: "Source code for these slides can be found [on GitHub](https://github.com/IndrajeetPatil/intro-to-snapshot-testing/){target='_blank'}."
#author: "Indrajeet Patil"
#affiliation:
execute:
echo: true
---
## Introduction to Snapshot Testing in R {style="margin-top: 1em;"}
<!-- Don't render this file manually. Run `renderer.R` script instead. -->
::: {style="margin-top: 0.5em; margin-bottom: 0.5em; font-size: 1em"}
Indrajeet Patil
:::
::: {style="margin-top: 1em; font-size:0.75em"}
![](media/logos_combined.jpeg){.absolute width="750" height="300"}
:::
## Unit testing {.smaller}
The goal of a unit test is to capture the *expected* output of a function using *code* and making sure that *actual* output after any changes matches the expected output.
[`{testthat}`](https://testthat.r-lib.org/) is a popular framework for writing unit tests in R.
:::: {.columns}
::: {.column width='60%'}
:::{.callout-important}
## Benefits of unit testing
- insures against unintentionally changing function behaviour
- prevents re-introducing already fixed bugs
- acts as the most basic form of developer-focused documentation
- catches breaking changes coming from upstream dependencies
- etc.
:::
:::
::: {.column width='40%'}
:::{.callout-tip}
## Test output
Test pass only when actual function behaviour matches expected.
| actual | expected | tests |
| ------- | ------- | ----- |
| {{< fa regular file-lines size=2xl >}} | {{< fa regular file-lines size=2xl >}} | {{< fa regular circle-check size=2xl >}} |
| {{< fa regular file size=2xl >}} | {{< fa regular file-lines size=2xl >}} | {{< fa regular circle-xmark size=2xl >}} |
:::
:::
::::
## Unit testing with `{testthat}`: A recap {.smaller}
:::: {.columns}
::: {.column width='50%'}
::: {.callout-important}
## Test organization
Testing infrastructure for R package has the following hierarchy:
| Component | Role |
| :------------------------------------------------------- | :-------------------------------------------------------------------- |
| <br> {{< fa regular file-code size=2xl >}} **Test file** | Tests for `R/foo.R` will typically be in `tests/testthat/test-foo.R`. |
| {{< fa solid flask size=2xl >}} **Tests** | A single file can contain multiple tests. |
| <br> {{< fa solid equals size=2xl >}} **Expectations** | A single test can have multiple expectations. |
:::
:::
::: {.column width='50%'}
:::{.callout-tip}
## Example test file
- Every test is a call to `testthat::test_that()` function.
- Every expectation is represented by `testthat::expect_*()` function.
- You can generate a test file using `usethis::use_test()` function.
```{.r}
# File: tests/testthat/test-op.R
# test-1
test_that("multiplication works", {
expect_equal(2 * 2, 4) # expectation-1
expect_equal(-2 * 2, -4) # expectation-2
})
# test-2
test_that("addition works", {
expect_equal(2 + 2, 4) # expectation-1
expect_equal(-2 + 2, 0) # expectation-2
})
...
```
:::
:::
::::
## What is different about snapshot testing?
. . .
A **unit test** records the code to describe expected output.
<br>
<!-- Need to install the Quarto extension for fontawesome to work:
https://github.com/quarto-ext/fontawesome -->
(actual) {{< fa regular file-code size=2xl >}} {{< fa solid arrows-left-right size=2xl >}} {{< fa solid file-code size=2xl >}} (expected)
<br>
. . .
A **snapshot test** records expected output in a separate, human-readable file.
<br>
(actual) {{< fa regular file-code size=2xl >}} {{< fa solid arrows-left-right size=2xl >}} {{< fa solid file-lines size=2xl >}} (expected)
## Why do you need snapshot testing?
If you develop R packages and have struggled to
::: incremental
- test that text output *prints* as expected
- test that an entire file *is* as expected
- test that generated graphical output *looks* as expected
- update such tests *en masse*
:::
. . .
then you should be excited to know more about *snapshot tests* (aka *golden tests*)! 🤩
# Prerequisites
Familiarity with writing unit tests using [`{testthat}`](https://testthat.r-lib.org/index.html){target="_blank"}.
If not, have a look at [this](https://r-pkgs.org/testing-basics.html){target="_blank"} chapter from *R Packages* book.
##
<br>
:::{.callout-important}
## *Nota bene*
In the following slides, in all snapshot tests, I include the following line of code:
```r
local_edition(3)
```
**You don't need to do this in your package tests!**
It's sufficient to update the `DESCRIPTION` file to use `{testthat}` 3rd edition:
```r
Config/testthat/edition: 3
```
For more, see [this](https://testthat.r-lib.org/articles/third-edition.html){target="_blank"} article.
:::
# Testing text outputs
Snapshot tests can be used to test that text output *prints* as expected.
Important for testing functions that pretty-print R objects to the console, create elegant and informative exceptions, etc.
## Example function {.smaller}
Let's say you want to write a unit test for the following function:
:::: {.columns}
::: {.column width='60%'}
**Source code**
```{r}
print_movies <- function(keys, values) {
paste0(
"Movie: \n",
paste0(" ", keys, ": ", values, collapse = "\n")
)
}
```
:::
::: {.column width='40%'}
**Output**
```{r}
cat(print_movies(
c("Title", "Director"),
c("Salaam Bombay!", "Mira Nair")
))
```
:::
::::
. . .
<br>
Note that you want to test that the printed output *looks* as expected.
Therefore, you need to check for all the little bells and whistles in the printed output.
## Example test {.smaller}
Even testing this simple function is a bit painful because you need to keep track of every escape character, every space, etc.
```{r, echo=FALSE}
library(testthat)
```
```{r}
test_that("`print_movies()` prints as expected", {
expect_equal(
print_movies(
c("Title", "Director"),
c("Salaam Bombay!", "Mira Nair")
),
"Movie: \n Title: Salaam Bombay!\n Director: Mira Nair"
)
})
```
. . .
With a more complex code, it'd be impossible for a human to reason about what the output is supposed to look like.
. . .
:::{.callout-important}
If this is a utility function used by many other functions, changing its behaviour would entail *manually* changing expected outputs for many tests.
This is not maintainable! 😩
:::
## Alternative: Snapshot test {.smaller}
Instead, you can use `expect_snapshot()`, which, when run for the first time, generates a Markdown file with expected/reference output.
```{r include = FALSE}
snapper <- local_snapshotter()
snapper$start_file("slides.qmd", "test")
```
```{r}
test_that("`print_movies()` prints as expected", {
local_edition(3)
expect_snapshot(cat(print_movies(
c("Title", "Director"),
c("Salaam Bombay!", "Mira Nair")
)))
})
```
```{r, include = FALSE}
# Reset snapshot test
snapper$end_file()
snapper$start_file("slides.qmd", "test")
```
. . .
:::{.callout-warning}
The first time a snapshot is created, it becomes *the truth* against which future function behaviour will be compared.
Thus, it is **crucial** that you carefully check that the output is indeed as expected. 🔎
:::
## Human-readable Markdown file {.smaller}
Compared to your unit test code representing the expected output
```r
"Movie: \n Title: Salaam Bombay!\n Director: Mira Nair"
```
notice how much more human-friendly the Markdown output is!
```md
Code
cat(print_movies(c("Title", "Director"), c("Salaam Bombay!", "Mira Nair")))
Output
Movie:
Title: Salaam Bombay!
Director: Mira Nair
```
It is easy to *see* what the printed text output is *supposed* to look like. In other words, snapshot tests are useful when the *intent* of the code can only be verified by a human.
. . .
:::{.callout-note}
## More about snapshot Markdown files
- If test file is called `test-foo.R`, the snapshot will be saved to `test/testthat/_snaps/foo.md`.
- If there are multiple snapshot tests in a single file, corresponding snapshots will also share the same `.md` file.
- By default, `expect_snapshot()` will capture the code, the object values, and any side-effects.
:::
## What test success looks like {.smaller}
If you run the test again, it'll succeed:
```{r}
test_that("`print_movies()` prints as expected", {
local_edition(3)
expect_snapshot(cat(print_movies(
c("Title", "Director"),
c("Salaam Bombay!", "Mira Nair")
)))
})
```
```{r, include = FALSE}
# Reset snapshot test
snapper$end_file()
snapper$start_file("slides.qmd", "test")
```
. . .
<br>
:::{.callout-note}
### Why does my test fail on a re-run?
If testing a snapshot you just generated fails on re-running the test, this is most likely because your test is not deterministic. For example, if your function deals with random number generation.
In such cases, setting a seed (e.g. `set.seed(42)`) should help.
:::
## What test failure looks like {.smaller}
When function changes, snapshot doesn't match the reference, and the test fails:
:::: {.columns}
::: {.column width='35%'}
**Changes to function**
```{.r code-line-numbers="5"}
print_movies <- function(keys, values) {
paste0(
"Movie: \n",
paste0(
" ", keys, "- ", values,
collapse = "\n"
)
)
}
```
```{r}
#| echo: false
print_movies <- function(keys, values) {
paste0(
"Movie: \n",
paste0(" ", keys, "- ", values, collapse = "\n")
)
}
```
<br>
Failure message provides expected (`-`) vs observed (`+`) diff.
:::
::: {.column width='65%'}
**Test failure**
```{.r}
test_that("`print_movies()` prints as expected", {
expect_snapshot(cat(print_movies(
c("Title", "Director"),
c("Salaam Bombay!", "Mira Nair")
)))
})
```
```{r, echo=FALSE, error=TRUE}
test_that("`print_movies()` prints as expected", {
local_edition(3)
expect_snapshot(cat(print_movies(
c("Title", "Director"),
c("Salaam Bombay!", "Mira Nair")
)))
})
```
:::
::::
## Fixing tests {.smaller}
Message accompanying failed tests make it explicit how to fix them.
. . .
- If the change was *deliberate*, you can accept the new snapshot as the current *truth*.
```r
* Run `snapshot_accept('foo.md')` to accept the change
```
- If this was *unexpected*, you can review the changes, and decide whether to change the snapshot or to correct the function behaviour instead.
```r
* Run `snapshot_review('foo.md')` to interactively review the change
```
. . .
<br>
:::{.callout-tip}
## Fixing multiple snapshot tests
If this is a utility function used by many other functions, changing its behaviour would lead to failure of many tests.
You can update *all* new snapshots with `snapshot_accept()`. And, of course, check the diffs to make sure that the changes are expected.
:::
## Capturing messages and warnings {.smaller}
So far you have tested text output printed to the console, but you can also use snapshots to capture messages, warnings, and errors.
:::: {.columns}
::: {.column width='50%'}
**message**
```{r}
f <- function() message("Some info for you.")
test_that("f() messages", {
local_edition(3)
expect_snapshot(f())
})
```
:::
::: {.column width='50%'}
**warning**
```{r}
g <- function() warning("Managed to recover.")
test_that("g() warns", {
local_edition(3)
expect_snapshot(g())
})
```
:::
::::
:::{.callout-tip}
Snapshot records both the *condition* and the corresponding *message*.
You can now rest assured that the users are getting informed the way you want! 😌
:::
## Capturing errors {.smaller}
In case of an error, the function `expect_snapshot()` itself will produce an error.
You have two ways around this:
:::: {.columns}
::: {.column width='50%'}
**Option-1** (recommended)
```{.r code-line-numbers="3"}
test_that("`log()` errors", {
local_edition(3)
expect_snapshot(log("x"), error = TRUE)
})
```
```{r, echo=FALSE}
test_that("`log()` errors", {
local_edition(3)
expect_snapshot(log("x"), error = TRUE)
})
```
:::
::: {.column width='50%'}
**Option-2**
```{.r code-line-numbers="3"}
test_that("`log()` errors", {
local_edition(3)
expect_snapshot_error(log("x"))
})
```
```{r, echo=FALSE}
test_that("`log()` errors", {
local_edition(3)
expect_snapshot_error(log("x"))
})
```
:::
::::
:::{.callout-tip}
### Which option should I use?
- If you want to capture both the code and the error message, use `expect_snapshot(..., error = TRUE)`.
- If you want to capture only the error message, use `expect_snapshot_error()`.
:::
## Further reading {.smaller}
- `{testthat}` article on [snapshot testing](https://testthat.r-lib.org/articles/snapshotting.html){target="_blank"}
- Introduction to [golden testing](https://ro-che.info/articles/2017-12-04-golden-tests){target="_blank"}
- Docs for [Jest](https://jestjs.io/docs/snapshot-testing){target="_blank"} library in JavaScript, which inspired snapshot testing implementation in `{testthat}`
# Testing graphical outputs
To create graphical expectations, you will use `{testthat}` extension package: [`{vdiffr}`](https://vdiffr.r-lib.org/){target="_blank"}.
## How does `{vdiffr}` work? {.smaller}
`{vdiffr}` introduces `expect_doppelganger()` to generate `{testthat}` expectations for graphics. It does this by writing SVG snapshot files for outputs!
. . .
The figure to test can be:
- a `ggplot` object (from `ggplot2::ggplot()`)
- a `recordedplot` object (from `grDevices::recordPlot()`)
- any object with a `print()` method
. . .
:::{.callout-note}
- If test file is called `test-foo.R`, the snapshot will be saved to `test/testthat/_snaps/foo` folder.
- In this folder, there will be one `.svg` file for every test in `test-foo.R`.
- The name for the `.svg` file will be sanitized version of `title` argument to `expect_doppelganger()`.
:::
## Example function {.smaller}
Let's say you want to write a unit test for the following function:
:::: {.columns}
::: {.column width='50%'}
**Source code**
```{r}
library(ggplot2)
create_scatter <- function() {
ggplot(mtcars, aes(wt, mpg)) +
geom_point(size = 3, alpha = 0.75) +
geom_smooth(method = "lm")
}
```
:::
::: {.column width='50%'}
**Output**
```{r}
#| out.width: "100%"
create_scatter()
```
:::
::::
. . .
Note that you want to test that the graphical output *looks* as expected, and this expectation is difficult to capture with a unit test.
## Graphical snapshot test {.smaller}
You can use `expect_doppelganger()` from `{vdiffr}` to test this!
. . .
The *first time* you run the test, it'd generate an `.svg` file with expected output.
```{r include = FALSE}
library(vdiffr)
snapper <- local_snapshotter()
snapper$start_file("slides.qmd", "test")
```
```{r}
test_that("`create_scatter()` plots as expected", {
local_edition(3)
expect_doppelganger(
title = "create scatter",
fig = create_scatter(),
)
})
```
```{r, include = FALSE}
# Reset snapshot test
snapper$end_file()
snapper$start_file("slides.qmd", "test")
```
. . .
:::{.callout-warning}
The first time a snapshot is created, it becomes *the truth* against which future function behaviour will be compared.
Thus, it is **crucial** that you carefully check that the output is indeed as expected. 🔎
You can open `.svg` snapshot files in a web browser for closer inspection.
:::
## What test success looks like {.smaller}
If you run the test again, it'll succeed:
```{r}
test_that("`create_scatter()` plots as expected", {
local_edition(3)
expect_doppelganger(
title = "create scatter",
fig = create_scatter(),
)
})
```
```{r, include = FALSE}
# Reset snapshot test
snapper$end_file()
snapper$start_file("slides.qmd", "test")
```
## What test failure looks like {.smaller}
When function changes, snapshot doesn't match the reference, and the test fails:
:::: {.columns}
::: {.column width='40%'}
**Changes to function**
```{.r code-line-numbers="3"}
create_scatter <- function() {
ggplot(mtcars, aes(wt, mpg)) +
geom_point(size = 2, alpha = 0.85) +
geom_smooth(method = "lm")
}
```
```{r}
#| echo: false
create_scatter <- function() {
ggplot(mtcars, aes(wt, mpg)) +
geom_point(size = 2, alpha = 0.85) +
geom_smooth(method = "lm")
}
```
:::
::: {.column width='60%'}
**Test failure**
<!-- Currently, doesn't work properly with on GHA workflow -->
<!-- The exact error is the following: -->
<!-- Error: Can't find `tests/testthat/` in current directory -->
```{.r}
test_that("`create_scatter()` plots as expected", {
local_edition(3)
expect_doppelganger(
title = "create scatter",
fig = create_scatter(),
)
})
── Failure ('<text>:3'): `create_scatter()` plots as expected ──────────────────
Snapshot of `testcase` to 'slides.qmd/create-scatter.svg' has changed
Run `testthat::snapshot_review('slides.qmd/')` to review changes
Backtrace:
1. vdiffr::expect_doppelganger(...)
3. testthat::expect_snapshot_file(...)
Error in `reporter$stop_if_needed()`:
! Test failed
```
:::
::::
## Fixing tests {.smaller}
Running `snapshot_review()` launches a Shiny app which can be used to either accept or reject the new output(s).
```{r}
#| echo: false
#| out.width: "60%"
knitr::include_graphics("media/shiny_app_graphics.mov")
```
##
:::{.callout-tip}
## Why are my snapshots for plots failing?! 😔
If tests fail even if the function didn't change, it can be due to any of the following reasons:
- R's graphics engine changed
- `{ggplot2}` itself changed
- non-deterministic behaviour
- changes in system libraries
For these reasons, snapshot tests for plots tend to be fragile and are not run on CRAN machines by default.
:::
## Further reading
- `{vdiffr}` package [website](https://vdiffr.r-lib.org/){target="_blank"}
# Testing entire files
Whole file snapshot testing makes sure that media, data frames, text files, etc. are as expected.
## Writing test {.smaller}
Let's say you want to test JSON files generated by `jsonlite::write_json()`.
:::: {.columns}
::: {.column width='50%'}
**Test**
```{r include = FALSE}
snapper <- local_snapshotter()
snapper$start_file("slides.qmd", "test")
```
```{r}
# File: tests/testthat/test-write-json.R
test_that("json writer works", {
local_edition(3)
r_to_json <- function(x) {
path <- tempfile(fileext = ".json")
jsonlite::write_json(x, path)
path
}
x <- list(1, list("x" = "a"))
expect_snapshot_file(r_to_json(x), "demo.json")
})
```
```{r, include = FALSE}
# Reset snapshot test
snapper$end_file()
snapper$start_file("slides.qmd", "test")
```
**Snapshot**
```json
[[1],{"x":["a"]}]
```
:::
::: {.column width='50%'}
:::{.callout-note}
- To snapshot a file, you need to write a helper function that provides its path.
- If a test file is called `test-foo.R`, the snapshot will be saved to `test/testthat/_snaps/foo` folder.
- In this folder, there will be one file (e.g. `.json`) for every `expect_snapshot_file()` expectation in `test-foo.R`.
- The name for snapshot file is taken from `name` argument to `expect_snapshot_file()`.
:::
:::
::::
## What test success looks like {.smaller}
If you run the test again, it'll succeed:
```{r}
# File: tests/testthat/test-write-json.R
test_that("json writer works", {
local_edition(3)
r_to_json <- function(x) {
path <- tempfile(fileext = ".json")
jsonlite::write_json(x, path)
path
}
x <- list(1, list("x" = "a"))
expect_snapshot_file(r_to_json(x), "demo.json")
})
```
```{r, include = FALSE}
# Reset snapshot test
snapper$end_file()
snapper$start_file("slides.qmd", "test")
```
## What test failure looks like {.smaller}
If the new output doesn't match the expected one, the test will fail:
```{.r code-line-numbers="11"}
# File: tests/testthat/test-write-json.R
test_that("json writer works", {
local_edition(3)
r_to_json <- function(x) {
path <- tempfile(fileext = ".json")
jsonlite::write_json(x, path)
path
}
x <- list(1, list("x" = "b"))
expect_snapshot_file(r_to_json(x), "demo.json")
})
```
```{r, error=TRUE}
#| echo: false
# File: tests/testthat/test-write-json.R
test_that("json writer works", {
local_edition(3)
r_to_json <- function(x) {
path <- tempfile(fileext = ".json")
jsonlite::write_json(x, path)
path
}
x <- list(1, list("x" = "b"))
expect_snapshot_file(r_to_json(x), "demo.json")
})
```
## Fixing tests {.smaller}
Running `snapshot_review()` launches a Shiny app which can be used to either accept or reject the new output(s).
```{r}
#| echo: false
knitr::include_graphics("media/json_snapshot.png")
```
## Further reading {.smaller}
Documentation for [`expect_snapshot_file()`](https://testthat.r-lib.org/reference/expect_snapshot_file.html){target="_blank"}
# Testing Shiny applications
To write formal tests for Shiny applications, you will use `{testthat}` extension package: [`{shinytest2}`](https://rstudio.github.io/shinytest2/){target="_blank"}.
## How does `{shinytest2}` work? {.smaller}
`{shinytest2}` uses a Shiny app (how meta! 😅) to record user interactions with the app and generate snapshots of the application's state. Future behaviour of the app will be compared against these snapshots to check for any changes.
. . .
Exactly how tests for Shiny apps in R package are written depends on how the app is stored.
There are two possibilities, and you will discuss them both separately.
. . .
<br>
:::: {.columns}
::: {.column width='50%'}
**Stored in `/inst` folder**
```
├── DESCRIPTION
├── R
├── inst
│ └── sample_app