Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 87 ยท Testing and Debugging

Testing Vue Apps

Learn what to test in a Vue app, how the test pyramid applies, and how Vitest, Vue Test Utils and Testing Library fit together, with a runnable mini runner.

Sooner or later every Vue app reaches a point where changing one component breaks something three screens away. Automated tests are the safety net for that moment: small programs that use your code and shout when it stops doing what you promised. They let you refactor, upgrade Vue or add features without clicking through the whole app by hand.

This lesson is the map. You will learn which kinds of tests exist, which ones deserve most of your time, which tools Vue developers use (Vitest, Vue Test Utils and Testing Library), and what a good test actually checks. The next lessons go deep: unit testing components and testing composables and stores.

Test runners need Node.js and a build setup, so they cannot run inside this site. Config files and real test files are shown as read-only code. The runnable examples use a tiny test runner written in a few lines of plain JavaScript, so you can see what a test framework does underneath.

The test pyramid

Tests differ in how much of your app they exercise and how fast they run. The classic picture is a pyramid: many cheap tests at the bottom, few expensive ones at the top.

flowchart TB
    E["End-to-end tests<br/>real browser, whole app<br/>few, slow, high confidence"]
    C["Component tests<br/>mount a component, click, read the DOM<br/>some, fast"]
    U["Unit tests<br/>plain functions, composables, stores<br/>many, very fast"]
    E --- C
    C --- U

Most of your tests should be unit and component tests; keep a handful of end-to-end tests for the critical journeys.

  • Unit tests call a function with input and check the output. A price formatter, a validation function or a store action is a perfect candidate. They run in milliseconds and pinpoint the failing line.
  • Component tests mount one component (with its children), simulate clicks and typing, and check what appears in the DOM. They are the workhorse of Vue testing, because components are where most of your logic meets the template.
  • End-to-end (E2E) tests drive a real browser through a running app: sign in, add an item to the cart, check out. Tools like Playwright and Cypress do this. They give the most confidence and cost the most time, so keep them for flows that must never break.

A lower layer is cheaper to write, faster to run and easier to debug. When you can test a rule as a plain function, do that instead of testing it through a mounted component.

The tools

Four names come up again and again.

Tool What it does
Vitest The test runner: finds test files, runs them, reports results, provides describe, it, expect, mocks and fake timers. It reuses your Vite config, so aliases and plugins just work.
Vue Test Utils The official library to mount components and interact with them: mount, wrapper.find, trigger, setValue, emitted().
Testing Library (@testing-library/vue) A layer on top of Vue Test Utils that pushes you to test like a user: find things by role and text, not by class names or component internals.
jsdom or happy-dom A fake browser DOM that runs inside Node, so component tests do not need a real browser.

Vitest alone is enough for unit tests. Add Vue Test Utils (or Testing Library) when you test components.

Here is a typical setup. This is read-only, because it needs a project with Vite:

JavaScript
// vite.config.js
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

export default defineConfig({
  plugins: [vue()],
  test: {
    environment: "jsdom",
    globals: true, // describe, it and expect without imports
  },
});

A first component test then looks like this:

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

describe("CounterButton", () => {
  it("counts clicks", async () => {
    const wrapper = mount(CounterButton);

    await wrapper.get("button").trigger("click");

    expect(wrapper.text()).toContain("Clicked 1 time");
  });
});

You run it with npx vitest (watch mode) or npx vitest run (once, for CI). Notice the shape: arrange (mount), act (click), assert (check the text). Almost every test you will ever write follows these three steps.

What a test runner does

A test framework feels magical until you see how small its core is. A test is a named function. The runner calls it, catches errors, and reports pass or fail. expect throws an error when a comparison is false. That is nearly all of it.

A test runner in 20 lines

Real runners add parallel execution, watch mode, mocks, coverage and nicer diffs, but the core idea is exactly this. When a test fails, you read the message, find the mismatch, and decide whether the code or the test is wrong.

What to test (and what not to)

The most important testing rule: test behavior, not implementation. A user does not care that your component uses a ref named count. They care that clicking the button makes the text say "Clicked 1 time". If a test reads wrapper.vm.count, it breaks the day you rename that variable, even though nothing the user sees has changed.

Good things to test:

  • What renders for given props and state: text, lists, empty states, error messages.
  • What users can do: clicking, typing, submitting, and what changes after.
  • What a component tells its parent: emitted events with the right payload.
  • Business rules: totals, discounts, validation, sorting, filtering. Put these in plain functions or composables so they are easy to test.
  • Edge cases and failures: empty lists, a failed request, invalid input.

Things to skip or limit:

  • Vue itself. You do not need a test proving that v-if hides things. Vue's own tests do that.
  • Private details: internal refs, method names, how many times something rendered.
  • Pure styling. A test that checks a CSS class is usually a copy of the template. Visual regression tools are better for looks.
  • Third-party libraries. Mock them at the boundary and test your own use of them.

A useful question before writing a test: "If this test fails, will it mean a real user would notice a bug?" If not, the test probably costs more than it earns.

Query like a user

Testing Library's guiding idea is to find elements the way a person (or a screen reader) does. Prefer, in this order:

  1. By role and accessible name: getByRole("button", { name: "Save" })
  2. By label text for form fields: getByLabelText("Email")
  3. By visible text: getByText("Your cart is empty")
  4. By test id (data-testid) only when nothing else works.

This habit gives you a bonus: if you cannot find a button by its role and name, a screen reader user probably cannot either, so the test doubles as an accessibility check (see Accessibility in Vue).

A Testing Library version of the earlier test, read-only:

JavaScript
import { render, screen } from "@testing-library/vue";
import userEvent from "@testing-library/user-event";
import CounterButton from "./CounterButton.vue";

it("counts clicks", async () => {
  const user = userEvent.setup();
  render(CounterButton);

  await user.click(screen.getByRole("button", { name: /clicked/i }));

  expect(screen.getByRole("button")).toHaveTextContent("Clicked 1 time");
});

Vue Test Utils and Testing Library are not rivals. Many teams use Vue Test Utils for its precise control (props, emitted events, stubs) and Testing Library for user-centered queries, or just one of the two. Pick one style per project and stay consistent.

Tests you can run on a component

You can already try the arrange-act-assert shape on a real Vue component, with no framework at all. This example mounts a counter into a detached element, clicks the button with a real DOM event, waits for Vue to update the DOM, and checks the text. Each step is exactly what mount, trigger and nextTick do for you in Vue Test Utils.

Arrange, act, assert on a Vue component

The last test shows the one Vue-specific trap you will meet constantly: DOM updates are batched and happen asynchronously (see DOM Update Timing and nextTick). A test that reads the DOM right after a click sees the old value. That is why Vue Test Utils' trigger returns a promise and you write await wrapper.trigger("click").

Where to start

You do not need a perfect strategy on day one. A practical order:

  1. Write unit tests for pure logic as you write it.
  2. Add a component test for each component with real behavior (forms, lists with filters, anything with conditions).
  3. Add a failing test whenever you fix a bug, so it can never return.
  4. Add a few E2E tests for sign-in and the money path.
  5. Run everything in CI on every push.

Coverage numbers can help you find untested code, but a high percentage does not mean good tests. A test with no assertion raises coverage and proves nothing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which layer of the test pyramid should contain the most tests?

    Lower layers run in milliseconds and point at the failing code. E2E tests give high confidence but are slow, so keep them for the most important journeys.
  2. 2. What is the job of Vitest compared with Vue Test Utils?

    Vitest runs tests and reports results. Vue Test Utils is the component-level library you call inside those tests.
  3. 3. Which test is the most resilient to refactoring?

    Testing what users see and do survives renames and rewrites of the internals. The other options depend on implementation details.
  4. 4. Why does a test usually need to await after triggering a click on a Vue component?

    The DOM is updated on the next tick. Awaiting trigger (or nextTick) lets Vue flush the update before you assert.

Summary

  • Tests protect you when you change code: unit tests for logic, component tests for behavior, a few E2E tests for critical journeys.
  • Vitest runs the tests, Vue Test Utils mounts and drives components, Testing Library adds user-focused queries, and jsdom provides a DOM in Node.
  • A test is arrange, act, assert; a runner is a function caller that catches errors.
  • Test behavior and output, not internal refs or method names, and prefer queries by role and label.
  • DOM updates are asynchronous, so await interactions before asserting.
  • Add a test for every bug you fix.

Next, mount real components and test props, events and async updates in Unit Testing Components.