Search code examples
vuejs3vitevitest

vue & vitest, data-v-[random-number] attribute being added to html


Introduction: I am working with vite and vitest, I am doing snapshot tests for components that are 100% template and do not contain any logic

Problem: data-v-[random-number] It is being added to the root element of each component and snapshots are always different

What i want: Understand why im getting this data-v-[random-number] and if possible, a way to avoid this problem

Short example code:

BaseText.vue:

<script setup lang="ts"></script>
<template>
    <span><slot></slot></span>
</template>

BaseText.spec.ts:

import { describe, it, expect } from "vitest";
import { shallowMount } from "@vue/test-utils";
import BaseText from "./BaseText.vue";

describe(name, () => {
    const wrapper = shallowMount(BaseText);
    it("MatchSnapshot", () => {
        expect(wrapper.html()).toMatchSnapshot();
    });
});

Error when runing tests:

 - Expected   ""<span data-v-25e5131c=""></span>""
  + Received   ""<span data-v-b3462088=""></span>""

Solution

  • You can use this library to remove the data-v attributes (does it automatically). It also covers many many other common things you'd need when using Snapshot testing with Vue.

    Despite having jest in the name, this works with Vitest as well.