DEV Community

Discussion on: Don't snapshot your UI components, make assertions!

Collapse
 
mmcgahan profile image
Michael McGahan

This post makes a good point about contract testing, which snapshot tests are not well suited for. However, UI components in particular also need to produce valid/intended HTML markup, which is very awkward to do with individual assertions, and very easy to accidentally break in subtle ways during development - snapshots are great for catching the stray empty <span>, or a classname that should be present but was accidentally removed or misspelled. In UI code, ordering of elements can also be important, but it would be awkward to write an assertion to test for ordering, and the result would be something more fragile and difficult to maintain than a corresponding snapshot test.

One way to frame this is that, although using assertions is more appropriate for ensuring that the component does what is expected for upstream code, in many cases snapshots are more appropriate for ensuring that the component correctly works with downstream (rendering) processes.

Either way, it's definitely valuable to think critically about which tool to use for a particular test - I just think that snapshots have particular value the closer you get to the front end - just make sure you're shallow rendering so that you're not double-testing nested components!