Testing components with Vitest and Vue Test Utils

Intermediate · 34 min

Mounting a Vue component in a test, passing props and slots, simulating input, asserting on output and emitted events, and testing with Pinia stores.

Before thisComponents and propsPinia fundamentals

Vue School · 34 min

Testing components with Vitest and Vue Test Utils

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Vue SchoolReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A component's public contract is its props and slots going in, and its rendered output and emitted events coming out; good component tests set the inputs and check the outputs without reading internal state.
  • Vitest runs tests through the same Vite pipeline as the app, so .vue files, TypeScript, and path aliases work in tests with no extra build setup; a DOM environment such as jsdom or happy-dom stands in for the browser.
  • Vue Test Utils' mount() renders a component into that DOM and returns a wrapper for finding elements, triggering events, setting input values, and reading emitted events.
  • Vue batches DOM updates, so after trigger(), setValue(), or setProps() you await the call before asserting; flushPromises() is the extra step when the component also waited on a promise like a mocked fetch.
  • createTestingPinia from @pinia/testing gives a component a fresh store with chosen initial state and spied, stubbed actions, so a component test can check that it called the store correctly without running the store's real logic.

What a component test is checking

Think of a component as a function with a wider interface. Going in: props, slots, and, for many components, a store or an injected value. Coming out: the DOM it renders and the events it emits. A component test sets the inputs, plays the part of the user, and checks the outputs.

What it should not check is how the component gets from one to the other. If a test reads a component’s internal ref or calls its private functions, it breaks every time you refactor, even when nothing a parent or a user could see has changed. Where component tests sit next to end-to-end and unit tests, and how many of each to write, is covered in frontend testing strategies. This lesson is about the Vue-specific mechanics.

The tools: Vitest and Vue Test Utils

Two libraries split the work:

  • Vitest is the test runner: it finds test files, runs them, and provides describe, it, expect, and mocking with vi. Its big advantage in a Vue project is that it reuses your Vite configuration, so .vue files, TypeScript, and import aliases work in tests exactly as they do in the app.
  • Vue Test Utils (VTU) is Vue’s official component-testing library. It mounts a component and gives you a wrapper to interact with it. Version 2 is the one for Vue 3; tutorials using createLocalVue or Jest with vue-jest are from the Vue 2 era.

Tests run in Node, so they need a fake DOM. A project created with npm create vue@latest and Vitest selected already has this configured:

// vitest.config.ts
import { fileURLToPath } from 'node:url'
import { mergeConfig, defineConfig, configDefaults } from 'vitest/config'
import viteConfig from './vite.config'

export default mergeConfig(
  viteConfig,
  defineConfig({
    test: {
      environment: 'jsdom',
      exclude: [...configDefaults.exclude, 'e2e/**'],
      root: fileURLToPath(new URL('./', import.meta.url)),
    },
  }),
)

Mounting, props, and finding things

Here’s a small component to test:

<!-- TodoItem.vue -->
<script setup lang="ts">
defineProps<{ id: number; text: string; done: boolean }>()
const emit = defineEmits<{ toggle: [id: number]; remove: [id: number] }>()
</script>

<template>
  <li :class="{ done }">
    <input type="checkbox" :checked="done" @change="emit('toggle', id)" />
    <span data-test="text">{{ text }}</span>
    <button data-test="remove" @click="emit('remove', id)">Remove</button>
  </li>
</template>

mount renders it with the props you choose and returns a wrapper:

// TodoItem.spec.ts
import { describe, expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
import TodoItem from './TodoItem.vue'

describe('TodoItem', () => {
  it('renders the text and the done state', () => {
    const wrapper = mount(TodoItem, {
      props: { id: 1, text: 'Buy milk', done: true },
    })

    expect(wrapper.get('[data-test="text"]').text()).toBe('Buy milk')
    expect(wrapper.classes()).toContain('done')
  })
})

get() throws a clear error if nothing matches, which is what you want for elements that must exist. find() returns an empty wrapper instead, so it pairs with .exists() when you’re asserting that something is not there. A data-test attribute is a stable hook that survives restyling, unlike a CSS class.

Simulating input and reading emitted events

User interaction goes through trigger() for events and setValue() for form fields. Both return a promise, and you should always await them.

it('emits remove with its id when the button is clicked', async () => {
  const wrapper = mount(TodoItem, { props: { id: 7, text: 'x', done: false } })

  await wrapper.get('[data-test="remove"]').trigger('click')

  expect(wrapper.emitted('remove')).toEqual([[7]])
})

emitted('remove') returns an array with one entry per emission, and each entry is the array of arguments, hence [[7]].

The await matters because Vue doesn’t update the DOM synchronously. State changes are batched and applied on the next tick, so an assertion right after a click would see the old DOM. Awaiting trigger, setValue, or setProps waits for that tick. When a component also waits on a promise of its own, such as a mocked fetch in onMounted, call await flushPromises() (exported by VTU) to let those promises settle before you assert.

Slots and global configuration go through the same mount options:

mount(Card, {
  props: { title: 'Plan' },
  slots: { default: '<p>Body text</p>' },
  global: {
    plugins: [router],
    stubs: { HeavyChart: true }, // replace one child with a stub
  },
})

shallowMount stubs every child component at once. It is handy for isolating a component with expensive children, but it also hides bugs at the boundary between parent and child, so prefer mount with targeted stubs.

Components that use a Pinia store

A component that reads from a store needs an active Pinia instance, or useCartStore() throws. @pinia/testing provides createTestingPinia, which you install as a plugin:

import { createTestingPinia } from '@pinia/testing'
import { vi } from 'vitest'
import { mount } from '@vue/test-utils'
import CartButton from './CartButton.vue'
import { useCartStore } from '@/stores/cart'

it('adds the product to the cart', async () => {
  const wrapper = mount(CartButton, {
    props: { productId: 42 },
    global: {
      plugins: [
        createTestingPinia({
          createSpy: vi.fn,
          initialState: { cart: { items: [] } }, // keyed by store id
        }),
      ],
    },
  })

  const cart = useCartStore() // the same testing store the component uses

  await wrapper.get('button').trigger('click')

  expect(cart.addItem).toHaveBeenCalledWith(42)
})

Two defaults to know. Every action is replaced with a spy and does not run, so the test checks the component’s side of the contract (“it asked the store to add item 42”) without depending on the store’s logic. Pass stubActions: false when you want the real actions. And createSpy: vi.fn tells Pinia which spy function to use, since it can’t assume your test runner.

The store itself is tested separately, as plain functions: call setActivePinia(createPinia()) in a beforeEach, create the store, call its actions, and assert on its state. No component needs to be mounted.

Coming from React Testing Library

If you’ve used React Testing Library, the main difference is philosophy. RTL deliberately gives you only user-facing queries (roles, labels, text). VTU is lower level: it lets you find components, read emitted events, and set props directly. That power is useful, since emitted events are a real part of a Vue component’s contract, but it also makes testing internals easy. @testing-library/vue exists and wraps VTU with the RTL-style API, if your team prefers that discipline.

What the video covers

Maya Shavin’s Vue.js Nation talk builds a component-testing setup with Vitest and Vue Test Utils 2 against a small movie-search app, testing both components and the composables behind them. It was recorded when Vitest was still pre-1.0, so some configuration details have moved on (Vitest is now on major version 5), but the VTU testing patterns are current. It doesn’t cover Pinia, which is why the store section above is here. LearnVue’s five-minute runner-up is the quickest refresher on mount and wrapper assertions.

Where this fits

Testing builds on components and props and Pinia fundamentals. Next: component libraries for Vue.

Check yourself

  1. 01Why is asserting on `wrapper.emitted('remove')` better than asserting that some internal `isRemoving` ref became true?

    The emitted event is part of the component's public contract, the thing a parent actually depends on. An internal ref is an implementation detail; renaming it or replacing it with a computed breaks the test even though the component behaves exactly the same to every parent that uses it.

  2. 02A test calls `wrapper.find('button').trigger('click')` and immediately asserts the counter text reads 1, but it still reads 0. What is wrong?

    Vue applies DOM updates asynchronously, batched into the next tick. `trigger` returns a promise that resolves after that update, so the test must `await` it before asserting on the DOM.

  3. 03By default, what happens when a component under `createTestingPinia()` calls one of the store's actions?

    The action is replaced by a spy and does not run, so the store's state doesn't change. The test can assert the action was called with the right arguments. Pass `stubActions: false` if you want the real action to execute.

  4. 04When would you use `shallowMount` instead of `mount`?

    When a component renders heavy or side-effecting children you want out of the way, `shallowMount` replaces every child component with a stub. It is used less than it once was, because stubbing everything also hides real integration bugs; many teams prefer `mount` and stub only specific children through `global.stubs`.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark