Since I moved to react at work I have been using and trying different testing strategies and I wanted to share some thoughts and best practices around snapshot testing.
In the past I have worked on different projects on frontend, from simple websites to complex editors. Along the journey I have used different testing frameworks and tools.
While recently snapshot testing has become popular, in my opinion it can be a double edged sword, and here is why.
Take a look to the following test:
it(‘is just a snapshot test’, () => {
const component = render()
expect(component).toMatchSnapshot()
})
Can you guess what’s the component behavior?
Now, let’s take the same component and test it in a different way:
it(‘is just a regular assert test’, () => {
const component = render()
expect(component.text()).toEqual(’April 4, 2020')
})
Now it is easier to guess, the component renders a formatted date!!!
This is a silly example, but tests are not only a way of proving correctness, they are also a way of documenting behavior. Snapshot testing will most of the time obfuscate that behavior making it harder to decipher it by reading the tests.
It is true that you could read the snapshot file and eventually get to the same result, but the fact that they are not even on the same file makes everything more error prone.
Another concern is that it can be easy for a snapshot test to get out of hand. We all have seen snapshots that are way over 500 lines. By then there are a couple of things that went wrong:
Finally snapshot testing will discourage doing integration tests as those will usually result in unmaintainable snapshot files.
I am Still learning and iterating on how to use snapshot testing best, but the biggest value I see is that they will tell you exactly what changed. So there are 2 places where they make most sense:
I still use snapshot testing a lot, sometimes more that I should! (probably because it is a quick way of testing). That being said, I try to follow these principles:
toMatchInlineSnapshot
for small components/objects. Following the original example, by using inlineSnapshot you can still provide readability to the test and document the use case properly.it(‘is using inline snapshots’, () => {
const component = render()
expect(component)
.toMatchInlineSnapshot('<div>April 4, 2020</div>')
})
Not convinced yet, here are some other posts that I found useful:
Enjoy!!!
Catch up with me on X (twitter):@juan_allo
---
@2024 Juan Manuel Allo Ron. All Rights reserved