Unit Testing Vue Components with Vitest
Think of it as a two-part system: Vue Test Utils mounts your component in a virtual environment, and a runner like Vitest executes the test and reports pass/fail. Use this to verify a component's logic in isolation.
WHY IT EXISTS To verify the behavior of individual Vue components without needing to run the entire application in a browser. This allows for fast, isolated feedback on component logic, ensuring that changes don't break its core functionality and contract.
THE MENTAL MODEL Think of it as a lab environment for your component. Vue Test Utils (@vue/test-utils) provides the workbench and tools (mount, find, trigger) to place your component under a microscope. Vitest is the lab technician who runs the predefined experiment (your test file) and records the results (pass or fail). Neither can do the job alone.
HOW IT WORKS A typical test involves three steps. First, you import mount from @vue/test-utils and the component you want to test. Second, inside a test block provided by Vitest, you call mount(MyComponent, { props: {...} }) to create an in-memory instance, which returns a wrapper object. Third, you use the wrapper API to interact with or inspect the component (e.g., wrapper.text(), wrapper.find('button')) and use Vitest's expect function to assert that the outcome is correct.
WHEN TO USE IT Use this combination for classic unit testing. For example: verifying that a component renders the correct text based on its props; ensuring a v-if directive correctly shows or hides an element; or confirming that a user click emits the expected event with the correct payload. It's for testing the component's contract in isolation.
WHEN NOT TO USE IT Avoid this for testing interactions between multiple complex components or for full end-to-end user flows. Tools like Cypress or Playwright (in their E2E mode) are better suited for testing how the entire application behaves in a real browser, including navigation and network interactions.
ONE CANONICAL EXAMPLE A canonical test checks if a component displays a message passed via props. You import mount from Vue Test Utils, expect and test from Vitest, and your component. Inside the test, you define a message string and create a wrapper by calling mount(MessageComponent, { props: { msg: your_message } }). The final step is the assertion: expect(wrapper.text()).toContain(your_message). This confirms the component correctly rendered its prop.
Read the original → test-utils.vuejs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.