Snapshot testing helps you check if your Vue components look the same as before. It catches unexpected changes easily.
Snapshot testing in Vue
import { mount } from '@vue/test-utils' import MyComponent from '@/components/MyComponent.vue' test('matches snapshot', () => { const wrapper = mount(MyComponent) expect(wrapper.html()).toMatchSnapshot() })
Use mount from @vue/test-utils to render the component.
toMatchSnapshot() saves the HTML output and compares it on future runs.
import { mount } from '@vue/test-utils' import Button from '@/components/Button.vue' test('Button snapshot', () => { const wrapper = mount(Button) expect(wrapper.html()).toMatchSnapshot() })
import { mount } from '@vue/test-utils' import List from '@/components/List.vue' test('List snapshot with props', () => { const wrapper = mount(List, { props: { items: ['apple', 'banana'] } }) expect(wrapper.html()).toMatchSnapshot() })
This test mounts a simple HelloWorld component and checks its HTML output against a saved snapshot. If the output changes, the test will fail, alerting you to unexpected UI changes.
import { mount } from '@vue/test-utils' import { describe, test, expect } from 'vitest' // Simple Vue component const HelloWorld = { template: `<div><h1>Hello, Vue!</h1></div>` } describe('HelloWorld snapshot test', () => { test('renders correctly', () => { const wrapper = mount(HelloWorld) expect(wrapper.html()).toMatchSnapshot() }) })
Snapshots are saved in a special folder and should be committed to your code repository.
If your component changes intentionally, update the snapshot by running the test command with the update flag (e.g., vitest -u).
Snapshot tests are fast but should be combined with other tests for full coverage.
Snapshot testing saves your component's HTML output to catch unexpected changes.
Use mount from @vue/test-utils and toMatchSnapshot() in your tests.
Update snapshots intentionally when your UI changes as planned.