7. Snapshot Testing Flashcards
What is a snapshot?
JSON-based record of a component’s output.
How does snapshot testing work?
A snapshot taken previously is compared to its corresponding component’s actual output. If everything matches, the test passes; otherwise, it fails.
What can be said about snapshots when it comes to source control?
Snapshots are committed along with other and tests to the application repo.
What do you need to import in a file in order to create a snapshot?
The component you’d like to create the snapshot of, and the renderer
from ‘react-test-renderer’.
eg.
~~~
import renderer from ‘react-test-renderer’;
import { MyComponent} from ‘./MyComponent’;
~~~
What do you use to create a tree?
The .create
method of the renderer
.
eg. const tree = renderer.create();
What is a tree in the context of snapshot testing?
A representation of the HTML output of the component.
How do you create a snapshot from a tree?
By using the toMatchSnapshot
assertion method and the toJSON
method of the tree— the first time toMatchSnapshot
is called, it creates the snapshot.
eg. expect(tree.toJSON()).toMatchSnapshot();
How do you assert that a tree matches a snapshot?
By using the toMatchSnapshot
assertion method and the toJSON
method of the tree — subsequent calls (after the first) to toMatchSnapshot
asserts whether it matches the existing snapshot.
eg. expect(tree.toJSON()).toMatchSnapshot();
What’s are the six potential steps of a snapshot testing process?
hint: Developer A vs Developer B
- Developer A authors a new component
- Snapshot of that component’s output is generated automatically
- Developer A commits changes, moves on
- - - Developer B makes a breaking change to a dependency of the new component
- A new snapshot is automatically generated
- Since the snapshots don’t match, the test suite will fail until updated.
What are the five advantages of snapshot testing?
- Fast and automatic
- Catches regressions humans may miss
- Works nicely with libraries that take in a state and output HTML components (React, Angular, Vue)
- Adds some protection against regression when no time is available for manually writing tests
- Requires little training or knowledge of testing to use
What are the six disadvantages of snapshot testing?
- Easy to ignore and suppress
- Protects only against regression
- If a component is working incorrectly and then is fixed, a snapshot test will say it is now broken
- Adds extra files to an already crowded repo
- Sensitive to incidental changes
- A waste of resources if the component in question is certain to be modified in the near future
How do you update snapshots?
By running the tests with an --update
flag.
eg. jest --update
When should we update snapshots?
Only when the developer has legitimately verified that the change to the broken component is not a regression but rather intended.