Jest Test Snapshots

A conventional unit test is written with a hard coded setup and hard coded assertions. If I wanted to test an isValidHex(myString) function using the standard approach I would probably conceive of a series of strings which I know are or aren't valid hex values. I would then run the function on those values in tern and verify the results with an assert(result).is(expected). I tell the computer how to set up the test, and how to read the results of the test, and then the computer tells me whether or not the test was successful. This allows me to run these tests again, later, in order to verify that I haven't broken a previously working test in the interim.

Jest snapshots work differently, but not as differently as some might think. When I initially write a snapshot, I still hard code the setup to the test, and identify the values who'd identity must be verified, but I don't hard code assertions against those values. Instead, upon running the test for the first time, Jest will save the state of those variables to a file—either a stand alone file, or, in the case of inline snapshots, in the test file itself. I still tell the computer how to set up the test, but this time I tell the computer whether or not the test was successful. The computer then knows how to verify results in the future, resulting in a continued utility for tests similar to the conventional unit test.

The only difference moving forward is that the snapshot can be updated instantly if the code is intentionally updated. What would have required new hand-written assertions can now be updated with a keystroke. Of course, the developer should still verify the new results, but those results can be printed in as simple a format as possible to accelerate the process. Essentially, both for new tests and old, snapshot testing trades writing of assertions with reading results.

Snapshot tests are most often attributed to testing user interface components, which is likely the result of Jest being associated with React, but snapshots are useful for any tests where reading values is faster than writing assertions. Which applies to many tests that must be written during any sufficiently large project. I've used snapshots to great effect when testing the value of date objects. It would be very difficult for me to remember the exact format of a printed date so that I could write an assertion. Having the computer print the date, and interpreting the format once I had it in front of me, was relatively quick and easy.

#software #testing #active