Snapshots
In this lesson, we will learn about a testing technique called Snapshot testing. Snapshot testing allows you to take a “snapshot” of the expected output of a component and compare it to the actual output produced during testing.
Snapshot tests are a very useful tool whenever you want to make sure the output of your functions doesn’t change unexpectedly.
When using snapshots, Vitest will take a snapshot of the given value, and then compare it to a reference snapshot file stored alongside the test. The test will fail if the two snapshots do not match: either the change is unexpected, or the reference snapshot needs to be updated to the new version of the result.
How to use Snapshots
To use snapshots in Vitest, you can use the toMatchSnapshot()
method from the expect()
API.
Let’s look at snapshots in action using our NotificationToast
component. Taking our first test in our Notification.test.js
, for example, we can create a simple snapshot test by modifying the assertion like so:
...
test("renders the correct style for error", () => {
const status = "error";
const wrapper = mount(notification, {
props: { status },
});
expect(wrapper.html()).toMatchSnapshot();
});
If we run our tests, we should see a snapshots folder automatically created for us in the same directory as our tests. Inside this folder, we can see our test file with an additional .snap
extension.
Inline Snapshots
Inline snapshots are another way to use snapshots in Vitest. Instead of creating a separate snapshot file, the expected output is saved directly in the test code. This can be useful for small and simple tests where creating and jumping across different files would seem tedious.
To use inline snapshots, you can use the toMatchInlineSnapshot()
method from the expect()
API.
Let’s modify our previous test for the NotificationToast
component to use an inline snapshot:
...
test("renders the correct style for error", () => {
const type = "error";
const wrapper = mount(notification, {
props: { status },
});
expect(wrapper.html()).toMatchInlineSnapshot(
`"<div role=\\\\"alert\\\\" class=\\\\"notification notification--error\\\\"><p class=\\\\"notification__text\\\\"></p><button title=\\\\"close\\\\" class=\\\\"notification__button\\\\"> ✕ </button></div>"`
);
});
This will save the snapshot directly in the test code, making it easier to manage for small tests.
Wrapping up
In this lesson, we learned about snapshot testing and how to use snapshots to speed up our testing process. Snapshot testing is a valuable tool for ensuring that the output of our components remains consistent over time. While snapshot testing has its benefits, it’s important to note that it may not be suitable for all kinds of tests and may become difficult to maintain over time.