Vue 3 Snapshot Serializer

2.13.2 · active · verified Sun Apr 19

Vue 3 Snapshot Serializer is a library designed to enhance snapshot testing for Vue 3 components within Vitest and Jest environments. It is currently at version 2.13.2 and actively maintained, with frequent minor releases incorporating bug fixes and new features. The library focuses on providing cleaner, more readable snapshots by intelligently handling Vue-specific elements like scoped styles, dynamic attributes, and prop serialization. A key differentiator is its explicit support for both `@vue/test-utils` and `@testing-library/vue`, offering flexible testing approaches. It directly addresses common snapshot noise, making tests more robust and less prone to irrelevant failures. This package is exclusively for Vue 3 projects, with a separate serializer available for Vue 2.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `vue3-snapshot-serializer` with Vitest, configure global snapshot settings to clean up output, and perform a basic component snapshot test.

/* vitest.setup.ts */
import { expect } from 'vitest';
import * as vue3SnapshotSerializer from 'vue3-snapshot-serializer';

// Add the serializer
expect.addSnapshotSerializer(vue3SnapshotSerializer);

// Configure global settings for cleaner snapshots
global.vueSnapshots = {
  removeComments: true, // Remove HTML comments
  removeDataTest: true, // Remove 'data-test' attributes
  removeDataTestid: true, // Remove 'data-testid' attributes
  removeDataVId: true, // Remove Vue's data-v-xxx attributes from scoped styles
  sortAttributes: true, // Sort attributes alphabetically for consistent snapshots
  formatter: 'diffable', // Use the 'diffable' formatter for improved readability
};

/* MyComponent.vue */
<template>
  <div class="container" data-test="my-container">
    <!-- My comment -->
    <p :style="{ color: dynamicColor }" data-testid="content">Hello {{ name }}!</p>
    <ChildComponent :value="{ a: 1, b: 'test' }" some-prop="static" />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

const name = ref('World');
const dynamicColor = ref('red');
</script>

/* ChildComponent.vue */
<template>
  <span class="child">{{ value.b }}</span>
</template>

<script setup lang="ts">
defineProps({
  value: Object,
  someProp: String,
});
</script>

/* MyComponent.test.ts */
import { mount } from '@vue/test-utils';
import { describe, it, expect } from 'vitest';
import MyComponent from './MyComponent.vue';

describe('MyComponent', () => {
  it('renders correctly', () => {
    const wrapper = mount(MyComponent);
    expect(wrapper.html()).toMatchSnapshot();
  });
});

view raw JSON →