TExcelTAD
Home › Vue › Vue Testing

Vue Testing

Automated tests check that your components keep working as you change code. Instead of clicking through the app by hand after every edit, you run a command and get a list of passed and failed checks within seconds.

Kinds of tests

Type What it checks Tools
Unit A single function or composable (formatPrice, useCounter) Vitest
Component One component: renders the right output, reacts to clicks, emits events Vitest + Vue Test Utils
End-to-end (E2E) The whole app in a real browser, like a user Playwright, Cypress

The official recommendation for Vite projects is Vitest (a fast test runner with a Jest-compatible API) together with @vue/test-utils (helpers to mount components). Both are installed when you tick "Vitest" in npm create vue@latest.

A component test

Given this component:

vue
<!-- src/components/CounterButton.vue -->
<script setup>
import { ref } from 'vue'
const props = defineProps({ start: { type: Number, default: 0 } })
const emit = defineEmits(['changed'])
const count = ref(props.start)
function inc() { count.value++; emit('changed', count.value) }
</script>

<template>
  <button @click="inc">Count: {{ count }}</button>
</template>

a test file next to it (or in __tests__/) could look like this:

js
// src/components/__tests__/CounterButton.spec.js
import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import CounterButton from '../CounterButton.vue'

describe('CounterButton', () => {
  it('renders the start value', () => {
    const wrapper = mount(CounterButton, { props: { start: 5 } })
    expect(wrapper.text()).toBe('Count: 5')
  })

  it('increments and emits on click', async () => {
    const wrapper = mount(CounterButton)
    await wrapper.find('button').trigger('click')   // await: let Vue update the DOM

    expect(wrapper.text()).toContain('Count: 1')
    expect(wrapper.emitted('changed')).toEqual([[1]])
  })
})

Run the tests:

bash · try it yourself
npx vitest run

 RUN  v3.2.4 /home/me/my-vue-app

 ✓ src/components/__tests__/CounterButton.spec.js (2 tests) 21ms
   ✓ CounterButton > renders the start value 9ms
   ✓ CounterButton > increments and emits on click 8ms

 Test Files  1 passed (1)
      Tests  2 passed (2)
   Start at  10:24:31
   Duration  812ms (transform 98ms, setup 0ms, collect 241ms, tests 21ms, environment 336ms, prepare 88ms)

npx vitest (without run) starts watch mode and re-runs affected tests on every save.

Vue Test Utils cheat-sheet

API Purpose
mount(Comp, { props, slots, global }) Render a component into a test DOM
wrapper.text(), wrapper.html() Read rendered output
wrapper.find('selector') / findAll Locate elements
await el.trigger('click') Fire a DOM event and wait for re-render
await input.setValue('abc') Type into an input (works with v-model)
wrapper.emitted('name') Array of argument lists for each emitted event
await wrapper.setProps({ … }) Change props
global: { plugins: [router, pinia] } Install plugins for the test

How it works: a mini test runner in the browser

Vue Test Utils is a thin layer over Vue itself: it calls createApp(Component).mount(element) on a detached element and inspects the DOM. You can do the same by hand. This playground "tests" a component with a tiny test() helper and prints PASS/FAIL:

html · try it yourself
<pre id="report" style="background:#111;color:#d1fae5;padding:10px"></pre>

<script type="module">
  import { createApp, nextTick, h } from 'vue';

  // ----- component under test -----
  const CounterButton = {
    props: { start: { type: Number, default: 0 } },
    emits: ['changed'],
    data() { return { count: this.start }; },
    methods: { inc() { this.count++; this.$emit('changed', this.count); } },
    template: `<button @click="inc">Count: {{ count }}</button>`
  };

  // ----- tiny "test utils" -----
  function mount(component, props = {}) {
    const el = document.createElement('div');
    const emitted = {};
    // wrap the component so we can record its emitted events
    const app = createApp({
      render: () => h(component, { ...props, onChanged: (...args) => (emitted.changed ||= []).push(args) })
    });
    app.mount(el);
    return { el, emitted, text: () => el.textContent, unmount: () => app.unmount() };
  }

  const results = [];
  async function test(name, fn) {
    try { await fn(); results.push('PASS  ' + name); }
    catch (e) { results.push('FAIL  ' + name + '\n      ' + e.message); }
  }
  function expectEqual(actual, expected) {
    if (JSON.stringify(actual) !== JSON.stringify(expected))
      throw new Error(`expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
  }

  // ----- the tests -----
  await test('renders the start value', () => {
    const w = mount(CounterButton, { start: 5 });
    expectEqual(w.text(), 'Count: 5');
  });

  await test('increments and emits on click', async () => {
    const w = mount(CounterButton);
    w.el.querySelector('button').click();
    await nextTick();                          // wait for Vue to update the DOM
    expectEqual(w.text(), 'Count: 1');
    expectEqual(w.emitted.changed, [[1]]);
  });

  await test('this one fails on purpose', async () => {
    const w = mount(CounterButton, { start: 1 });
    expectEqual(w.text(), 'Count: 2');
  });

  document.getElementById('report').textContent = results.join('\n');
  results.forEach(r => console.log(r));
</script>

Notice await nextTick(): Vue batches DOM updates, so after a click the DOM changes on the next "tick". Vue Test Utils' await trigger() does this for you.

Testing a composable

Composables that don't use lifecycle hooks are just functions — test them directly, no mounting needed:

html · try it yourself
<script type="module">
  import { ref, computed } from 'vue';

  function useCart() {
    const items = ref([]);
    const total = computed(() => items.value.reduce((s, i) => s + i.price * i.qty, 0));
    const add = (p) => {
      const line = items.value.find(i => i.id === p.id);
      line ? line.qty++ : items.value.push({ ...p, qty: 1 });
    };
    return { items, total, add };
  }

  const cart = useCart();
  cart.add({ id: 1, price: 4 });
  cart.add({ id: 1, price: 4 });
  cart.add({ id: 2, price: 10 });

  console.log(cart.items.value.length === 2 ? 'PASS  merges duplicate lines' : 'FAIL  merges duplicate lines');
  console.log(cart.total.value === 18 ? 'PASS  total is 18' : 'FAIL  total is ' + cart.total.value);
</script>

Tip: Test behaviour, not implementation: "clicking Add shows 1 item" survives refactoring, while "the items array has length 1" breaks as soon as you rename a variable.

Note: Vitest runs in Node, with a simulated DOM from jsdom or happy-dom (environment: 'jsdom' in vite.config.js). For things a fake DOM can't do — real layout, scrolling, multiple pages — use an E2E tool like Playwright.

Test yourself

Which function from @vue/test-utils renders a component for testing?

  1. render()
  2. mount()
  3. createTest()
  4. shallow()

Why do you await after trigger('click')?

  1. Clicks are async network calls
  2. Vue updates the DOM asynchronously (on the next tick)
  3. Vitest requires every line to be awaited
  4. To slow the test down

Which kind of test runs the whole app in a real browser like a user would?

  1. Unit test
  2. Component test
  3. End-to-end test
  4. Snapshot test