0
0
Vueframework~5 mins

Snapshot testing in Vue

Choose your learning style9 modes available
Introduction

Snapshot testing helps you check if your Vue components look the same as before. It catches unexpected changes easily.

You want to make sure your component's output stays the same after code changes.
You are adding new features and want to confirm old parts don't break.
You want a quick way to test UI without writing many detailed tests.
You want to track changes in your component's rendered HTML over time.
Syntax
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.

Examples
This tests that the Button component's HTML matches the saved snapshot.
Vue
import { mount } from '@vue/test-utils'
import Button from '@/components/Button.vue'

test('Button snapshot', () => {
  const wrapper = mount(Button)
  expect(wrapper.html()).toMatchSnapshot()
})
This tests the List component with specific props and saves its HTML snapshot.
Vue
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()
})
Sample Program

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.

Vue
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()
  })
})
OutputSuccess
Important Notes

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.

Summary

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.