Should I love or hate Snapshots?

Snapshot testing gave us a cheap and fast testing solution at the beginning. What happened next?

When we started a project we needed to have a fast and cheap way to keep our React components under control. We have started to use Snapshots like that.

it('matches snapshot', () => {
const { container } = render(<ContactsPageComponent />)
expect(container).toMatchSnapshot()
})

At the beginning it was really fast, cheap and very nice.

Later we found that usually we need also to be sure there is a match with a snapshot, but it’s better if we have a plain and straightforward expectation like that.

it('matches snapshot', () => {
const { container } = render(<ContactsPageComponent />)

expect(container)
.toEqual(expect.stringContaining('Phone: +555 000 00 11'))

expect(container)
.not.toEqual(expect.stringContaining('Skype'))

expect(container).toMatchSnapshot()
})

Snapshot tests usually show not only a difference in copies, but also a lot of diffs in the HTML markup. What is absolutely pointless from our perspective. Why? Because we use a third-party UI library to build our application and very often after we have this UI lib updated we have many diffs in classes’ names.

Finally we found that now snapshots do not give us too much value. Or at least, we should not use them together with other expectation statements. Because snapshots make output polluted with diffs in HTML markup.

Lessons I’ve learned.

  1. Snapshots is a cheap and fast way to keep your React components under control.
  2. Cheap and fast doesn’t mean good and effective. Do not be surprised when snapshots start playing against you.
  3. Always better to keep snapshots in separated specs and do not mix them with other expectation statements. In this way snapshots will not disturb you and prevent you from understanding a real issue in tests.
  4. Snapshots is not a best testing tool when you use third-party UI framework and you can not know when your markup is changed.

I hope this information will help you once.

Have a happy testing!

--

--

--

I’m front-end developer and really passionate programmer, caring husband and pancake baker on Sundays. School teacher of computer studies in the past.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ilya Zykin

Ilya Zykin

I’m front-end developer and really passionate programmer, caring husband and pancake baker on Sundays. School teacher of computer studies in the past.

More from Medium

Introduction to Redux

Use Chrome devtools understanding Closure .

Window is undefined during SSR

No more Switch / Cases (Or, most part of them)