Save Time on Expensive Bug Fixing with Snapshot Testing

Meet Jon, a Front-end Engineer at TED, living in the beautiful city of Denver, Colorado. He began writing code when he was 10 years old; with the help of Geocities, Microsoft FrontPage, and a little bit of HTML Goodies, he started on the journey that’s led him to where he is today.

Over the last 15+ years, Jon has published countless lines of code that has been seen or encountered by millions. He is passionate about high performance, accessible websites that deliver rich experiences to their users. We’re proud to have him as a consulting blogger, and friend.

What is snapshot testing?

Snapshot testing is a form of regression testing that verifies that your UI does not change unexpectedly. A snapshot test does not test the visual representation of a component but instead uses a JSON representation of a rendered element. You can think of it kind of it a little like copying markup from the browser inspector, except that snapshot tests, also contain useful things like props, inline event handlers, etc.

In the purest form, a snapshot test would look something like the following. Let’s say we have just a stateless, functional component called App that just spits out a div with some text in it.

// App.js
import React from 'react';

const App = () => (
	<div className="App">
		Snapshot test!

export default App;

We could write a pretty simple snapshot test that would look like:

// App.test.js
import React from 'react';
import renderer from 'react-test-renderer';
import App from './App';

test('App renders correctly', () => {
	const tree = renderer.create(
		<App />

Which, when run, would give us a .snap file that looks like:

// __snapshots__/App.test.js.snap
exports[`App renders correctly 1`] = `
  Snapshot test!
Want More ?

We offer a free strategy session for businesses of all sizes.

Sign Up Now

Start typing and press Enter to search