Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 87 ยท Testing and Debugging

Unit Testing Components

Mount Vue components in tests, check props, simulate clicks and typing, assert emitted events, handle async updates and use snapshots wisely, with a harness.

A component test answers one question: given these props and these user actions, does the component show the right things and tell its parent the right things? You mount the component into a fake page, interact with it the way a person would, and assert on the result. Because components are the unit of everything in Vue, this is the kind of test you will write most.

This lesson uses Vue Test Utils (VTU) for the real-world code and a hand-written mini version for the live examples. The mini version has the same method names for the parts you use daily (mount, find, trigger, setValue, setProps, emitted), so what you learn transfers directly.

Real tests need Node, Vitest and a build step, so the Vue Test Utils examples below are read-only. The runnable examples use a harness of about 40 lines that you can read in full. Treat it as a way to see what mount really does, not as a replacement for VTU.

The anatomy of a component test

Here is the component we will test. It is a small form that emits an add event with the text the user typed:

VUE
<!-- TodoInput.vue -->
<script setup>
import { ref, computed } from "vue";

defineProps({
  placeholder: { type: String, default: "What needs doing?" },
});
const emit = defineEmits(["add"]);

const text = ref("");
const canAdd = computed(() => text.value.trim() !== "");

function submit() {
  if (!canAdd.value) return;
  emit("add", text.value.trim());
  text.value = "";
}
</script>

<template>
  <form @submit.prevent="submit">
    <input v-model="text" :placeholder="placeholder" aria-label="New todo" />
    <button :disabled="!canAdd">Add</button>
  </form>
</template>

A Vue Test Utils test for it, read-only:

JavaScript
import { mount } from "@vue/test-utils";
import { describe, it, expect } from "vitest";
import TodoInput from "./TodoInput.vue";

describe("TodoInput", () => {
  it("emits add with the trimmed text and clears the field", async () => {
    const wrapper = mount(TodoInput);

    await wrapper.get("input").setValue("  Buy milk  ");
    await wrapper.get("form").trigger("submit");

    expect(wrapper.emitted("add")).toEqual([["Buy milk"]]);
    expect(wrapper.get("input").element.value).toBe("");
  });
});

Three steps again: arrange (mount), act (setValue, trigger), assert (emitted, the input's value). The return value of mount is a wrapper around the component: a handle with methods to look inside and poke at it.

flowchart LR
    T["Test"] -->|"mount(Component, props)"| W["Wrapper"]
    W -->|"find / get"| D["Rendered DOM"]
    T -->|"trigger / setValue"| D
    D -->|"events"| C["Component logic"]
    C -->|"re-render"| D
    C -->|"emit"| E["emitted() records"]
    T -->|"expect(...)"| D
    T -->|"expect(...)"| E

A test sits outside the component: it supplies props, drives the DOM like a user, and reads back the DOM and the recorded events.

Props: what goes in

Pass props as the props mounting option. Test each behavior a prop controls, including its default:

JavaScript
it("uses the default placeholder", () => {
  const wrapper = mount(TodoInput);
  expect(wrapper.get("input").attributes("placeholder")).toBe("What needs doing?");
});

it("uses a custom placeholder", () => {
  const wrapper = mount(TodoInput, { props: { placeholder: "Add a task" } });
  expect(wrapper.get("input").attributes("placeholder")).toBe("Add a task");
});

Props can change over time, and a good test checks that the component reacts. Use await wrapper.setProps({ ... }). It updates the props and waits for the DOM to catch up.

Remember one-way data flow: a test should never try to change a prop from inside the component. Change it from outside with setProps, like a parent would.

Events: what comes out

Components talk to their parents with emitted events. VTU records every emit, so you can assert on them:

  • wrapper.emitted("add") returns an array of calls, and each call is an array of arguments. Two emits of "a" and "b" give [["a"], ["b"]].
  • wrapper.emitted("add") is undefined if the event was never emitted, which is how you assert "nothing happened".
  • For v-model on components, look for update:modelValue.

Test the payload, not only the fact that something was emitted. An add event with the wrong text is still a bug.

A mini harness you can run

Now let's see this in action in the browser. The first block below is the harness. mount creates a host element, renders the component through a small wrapper component, and records every event the component declares in emits. The wrapper's trigger and setValue dispatch real DOM events and then wait for nextTick, just like VTU. Below it is TodoInput as a runnable template-string component and four tests.

Mounting and testing TodoInput

Notice that no test peeks at text or canAdd inside the component. Everything is checked through the DOM and the emitted events: what a parent and a user can observe.

Interacting like a user

Vue Test Utils gives you a small set of verbs, all returning promises that resolve after the DOM has updated:

Method What it does
wrapper.trigger("click") Dispatches a DOM event on an element (trigger("keydown.enter") works too)
wrapper.setValue("text") Sets an input, textarea or select value and fires the right event for v-model
wrapper.setProps({ ... }) Changes props from outside
wrapper.find(sel) / get(sel) Looks up an element; find returns an empty wrapper if missing, get throws

Always await them. Forgetting an await is the number one cause of "my test sees the old value" confusion, because Vue updates the DOM on the next tick.

Testing a v-model component and prop changes

A rating widget is a nice second example, because it has an incoming prop (modelValue), an outgoing event (update:modelValue) and a view that depends on the prop. The test also proves the stale-DOM rule: right after a click, before the next tick, the page has not re-rendered.

Testing a star rating

The third test is worth a second look. It documents the contract of a controlled component: the star rating never keeps its own state, so a click only produces an event, and the parent decides whether to accept it.

Async work and flushPromises

Updates caused by Vue (clicks, setValue, setProps) settle after one await. Updates caused by your own promises, such as a fetch finishing, need more: the promise must resolve first, and then Vue re-renders. VTU ships a helper for that:

JavaScript
import { mount, flushPromises } from "@vue/test-utils";

it("shows the user after loading", async () => {
  const wrapper = mount(UserCard, { props: { id: 1 } });
  expect(wrapper.text()).toContain("Loading");

  await flushPromises(); // let pending promises resolve, then the re-render

  expect(wrapper.text()).toContain("Ada Lovelace");
});

The component must get its data from something you control (a mocked fetch, or an injected function), never from the real network. The next lesson shows how to mock fetch.

Stubs, slots and global options

Some more options of mount that you will meet quickly (all read-only):

JavaScript
mount(Card, {
  props: { title: "Hello" },
  slots: {
    default: "<p>Body text</p>",
    footer: "<button>OK</button>",
  },
  global: {
    stubs: { HeavyChart: true },            // replace a child with an empty stub
    provide: { theme: "dark" },             // values for inject()
    mocks: { $t: (key) => key },            // fake global properties
    plugins: [],                            // e.g. a router or store
  },
});

mount renders children for real; shallowMount stubs all of them. Prefer mount and stub only what is slow, noisy or irrelevant. A test that renders real children catches real integration bugs, such as a parent passing a prop the child no longer accepts.

Snapshot tests: handle with care

A snapshot test saves the rendered HTML the first time and fails when it changes later:

JavaScript
it("renders the card", () => {
  const wrapper = mount(Card, { props: { title: "Hello" } });
  expect(wrapper.html()).toMatchInlineSnapshot();
});

Snapshots are quick to write and tell you that something changed, but not whether the change matters. In big components they fail on every small template edit, people get used to pressing "update", and real regressions slip through. A healthier rule:

  • Use snapshots for small, stable output (a formatted table row, a serialized object).
  • Prefer explicit assertions (expect(wrapper.text()).toContain(...)) for behavior.
  • Review snapshot diffs like code, never approve them blindly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a Vue Test Utils test, what does wrapper.emitted('add') return after the component emitted add once with the argument 'Buy milk'?

    emitted() records every call; each call is itself an array of the arguments. An event that was never emitted gives undefined.
  2. 2. Why should a test change a prop with wrapper.setProps instead of modifying it inside the component?

    A component must not mutate its props. The test plays the parent's role and passes new values in from outside.
  3. 3. A test clicks a button and immediately reads the DOM, but sees the old text. What is the most likely fix?

    Vue applies DOM updates on the next tick. Awaiting trigger waits for it.
  4. 4. When is flushPromises needed rather than just awaiting trigger?

    trigger and setProps wait for Vue's own update. A promise that resolves later (a mocked request) needs flushPromises before the re-render happens.
  5. 5. What is the main risk of large snapshot tests?

    Noisy snapshots train people to accept every diff, which hides real regressions. Use them for small stable output and explicit assertions for behavior.

Summary

  • A component test mounts the component, interacts like a user, and asserts on the DOM and on emitted events.
  • Pass props with mount(..., { props }) and change them later with await wrapper.setProps(...).
  • emitted("name") returns an array of argument arrays, or undefined if nothing was emitted.
  • trigger and setValue dispatch real DOM events; always await them, because Vue updates the DOM on the next tick.
  • Use flushPromises when the component waits for your own promises, and mock the network.
  • Mount real children by default; stub only what is slow or irrelevant.
  • Keep snapshots small and review their diffs.

Next up: logic that has no template of its own, in Testing Composables and Stores.