@testing-library/vue vs @vue/test-utils
Vue Component Testing Strategies
@testing-library/vue@vue/test-utilsSimilar Packages:

Vue Component Testing Strategies

@testing-library/vue and @vue/test-utils are the two primary libraries for testing Vue.js applications, but they serve different goals. @vue/test-utils is the official low-level utility library that provides direct access to component instances, lifecycle hooks, and internal state, making it ideal for unit testing component internals. @testing-library/vue is built on top of Vue testing primitives and focuses on testing components from the user's perspective, encouraging queries based on accessibility roles and visible text rather than implementation details. While @vue/test-utils gives you full control over the mounting process, @testing-library/vue abstracts away the mounting logic to prevent tests from becoming too coupled to the component structure.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
@testing-library/vue01,12230.5 kB362 years agoMIT
@vue/test-utils01,1441.49 MB4011 hours agoMIT

Vue Component Testing: @testing-library/vue vs @vue/test-utils

Both @testing-library/vue and @vue/test-utils help you verify that your Vue components work as expected, but they approach testing from opposite directions. One focuses on the user experience, while the other focuses on the component internals. Let's compare how they handle common testing tasks.

🧠 Core Philosophy: User Behavior vs Implementation Details

@testing-library/vue encourages testing behavior.

  • You query elements by their role or visible text.
  • Tests remain valid even if you change class names or structure.
// @testing-library/vue: Query by role
import { render, screen } from '@testing-library/vue'
import Button from './Button.vue'

render(Button, { props: { label: 'Submit' } })
const button = screen.getByRole('button', { name: 'Submit' })

@vue/test-utils exposes implementation details.

  • You query elements by CSS selectors or component references.
  • Tests may break if you refactor the DOM structure.
// @vue/test-utils: Query by CSS selector
import { mount } from '@vue/test-utils'
import Button from './Button.vue'

const wrapper = mount(Button, { props: { label: 'Submit' } })
const button = wrapper.find('button.submit-btn')

🏗️ Rendering Components: render vs mount

@testing-library/vue uses render.

  • It attaches the component to a container managed by the library.
  • Cleanup happens automatically after each test.
// @testing-library/vue: Render function
import { render } from '@testing-library/vue'

const { container } = render(MyComponent)
// container holds the DOM node

@vue/test-utils uses mount or shallowMount.

  • It returns a wrapper object that holds the component instance.
  • You must manually handle cleanup in some setups.
// @vue/test-utils: Mount function
import { mount } from '@vue/test-utils'

const wrapper = mount(MyComponent)
// wrapper contains the component instance and DOM

🔍 Querying Elements: Accessibility vs Selectors

@testing-library/vue prefers accessibility queries.

  • Uses getByRole, getByText, getByLabelText.
  • Ensures your app is accessible to screen readers.
// @testing-library/vue: Accessibility query
import { screen } from '@testing-library/vue'

const input = screen.getByLabelText('Username')
const heading = screen.getByRole('heading', { level: 1 })

@vue/test-utils prefers CSS selectors.

  • Uses find, get, findAll with strings or components.
  • Gives precise control over specific DOM nodes.
// @vue/test-utils: CSS selector query
import { mount } from '@vue/test-utils'

const wrapper = mount(MyComponent)
const input = wrapper.find('input[name="username"]')
const child = wrapper.findComponent(ChildComponent)

🖱️ User Interactions: fireEvent vs trigger

@testing-library/vue uses fireEvent or userEvent.

  • Simulates real browser events like clicks and typing.
  • Encourages testing complete user flows.
// @testing-library/vue: Fire event
import { fireEvent } from '@testing-library/vue'

await fireEvent.click(button)
await fireEvent.update(input, 'new value')

@vue/test-utils uses trigger.

  • Triggers Vue event listeners directly on the wrapper.
  • Faster but less representative of real browser behavior.
// @vue/test-utils: Trigger event
import { mount } from '@vue/test-utils'

await wrapper.find('button').trigger('click')
await wrapper.find('input').setValue('new value')

🔓 Accessing Internals: Discouraged vs vm

@testing-library/vue hides the component instance.

  • Direct access to vm is not provided by default.
  • Prevents tests from relying on internal state.
// @testing-library/vue: No direct VM access
// You interact only with the DOM
const { container } = render(MyComponent)
// No wrapper.vm available

@vue/test-utils exposes the component instance.

  • You can access wrapper.vm to check data or call methods.
  • Useful for testing logic that does not affect the DOM.
// @vue/test-utils: Direct VM access
import { mount } from '@vue/test-utils'

const wrapper = mount(MyComponent)
expect(wrapper.vm.count).toBe(0)
wrapper.vm.increment()

🤝 Similarities: Shared Ground Between Libraries

While the differences are clear, both libraries also share many core ideas and tools. Here are key overlaps:

1. ⚛️ Both Support Vue 3 Composition API

  • Both work with setup() functions and reactive refs.
  • Support testing components written with <script setup>.
// Both: Testing Composition API
// Component uses setup()
// Tests mount/render the same way regardless of API style

2. 🛠️ Both Require Vue Test Environment

  • Both need a valid Vue application context.
  • Both handle component registration and props similarly.
// Both: Passing props
// @testing-library/vue
render(Component, { props: { id: 1 } })

// @vue/test-utils
mount(Component, { props: { id: 1 } })

3. ✅ Both Support Async Components

  • Both handle await for async setup or data fetching.
  • Allow waiting for DOM updates before assertions.
// Both: Waiting for updates
// @testing-library/vue
await screen.findByText('Loaded')

// @vue/test-utils
await wrapper.vm.$nextTick()

4. 🧩 Both Support Global Plugins

  • Both allow installing Vuex, Pinia, or Vue Router for tests.
  • Ensure components have access to global state.
// Both: Global plugins
// @testing-library/vue
render(Component, { global: { plugins: [router] } })

// @vue/test-utils
mount(Component, { global: { plugins: [router] } })

📊 Summary: Key Differences

Feature@testing-library/vue@vue/test-utils
Philosophy🧠 User behavior🛠️ Implementation details
Rendering🏗️ render🏗️ mount
Querying🔍 Accessibility roles🔍 CSS selectors
Interactions🖱️ fireEvent🖱️ trigger
Internals🔒 Hidden (vm not exposed)🔓 Exposed (wrapper.vm)
Best For✅ Integration & E2E-like tests✅ Unit tests & libraries

💡 The Big Picture

@testing-library/vue is like a black-box tester 📦 — it cares only about inputs and outputs. Ideal for feature tests, accessibility compliance, and ensuring stability during refactors.

@vue/test-utils is like a white-box tester 🔍 — it lets you inspect the inner workings. Perfect for unit testing complex logic, reusable libraries, or when you need to mock deep child components.

Final Thought: Many teams use both. Use @testing-library/vue for high-level feature tests and @vue/test-utils for low-level unit tests where internal state matters. Choose based on what you need to prove.

How to Choose: @testing-library/vue vs @vue/test-utils

  • @testing-library/vue:

    Choose @testing-library/vue if your priority is testing what the user sees and interacts with, rather than how the component works internally. It is the best fit for integration tests, accessibility testing, and ensuring your UI behaves correctly across changes. This library forces you to write resilient tests that do not break when you refactor internal logic, as long as the user experience remains the same.

  • @vue/test-utils:

    Choose @vue/test-utils if you need to test private methods, internal state, or lifecycle hooks directly. It is suitable for unit testing reusable component libraries where you need to mock children deeply or assert on emitted events with precise control. This tool is also necessary if you are testing complex logic that does not render visible UI elements or requires direct access to the component instance.

README for @testing-library/vue

Vue Testing Library


lizard

Simple and complete Vue.js testing utilities that encourage good testing practices.

Vue Testing Library is a lightweight adapter built on top of DOM Testing Library and @vue/test-utils.


Read the docs | Edit the docs



Coverage Status GitHub version npm version Discord MIT License

Table of Contents

Installation

This module is distributed via npm and should be installed as one of your project's devDependencies:

npm install --save-dev @testing-library/vue

This library has peerDependencies listings for Vue 3 and @vue/compiler-sfc.

You may also be interested in installing jest-dom so you can use the custom Jest matchers.

If you're using Vue 2, please install version 5 of the library:

npm install --save-dev @testing-library/vue@^5

A basic example

<template>
  <p>Times clicked: {{ count }}</p>
  <button @click="increment">increment</button>
</template>

<script>
  export default {
    name: 'Button',
    data: () => ({
      count: 0,
    }),
    methods: {
      increment() {
        this.count++
      },
    },
  }
</script>
import {render, screen, fireEvent} from '@testing-library/vue'
import Button from './Button'

test('increments value on click', async () => {
  // The `render` method renders the component into the document.
  // It also binds to `screen` all the available queries to interact with
  // the component.
  render(Button)

  // queryByText returns the first matching node for the provided text
  // or returns null.
  expect(screen.queryByText('Times clicked: 0')).toBeTruthy()

  // getByText returns the first matching node for the provided text
  // or throws an error.
  const button = screen.getByText('increment')

  // Click a couple of times.
  await fireEvent.click(button)
  await fireEvent.click(button)

  expect(screen.queryByText('Times clicked: 2')).toBeTruthy()
})

You might want to install jest-dom to add handy assertions such as .toBeInTheDocument(). In the example above, you could write expect(screen.getByText('Times clicked: 0')).toBeInTheDocument().

Using byText queries it's not the only nor the best way to query for elements. Read Which query should I use? to discover alternatives. In the example above, getByRole('button', {name: 'increment'}) is possibly the best option to get the button element.

More examples

You'll find examples of testing with different situations and popular libraries in the test directory.

Some included are:

Feel free to contribute with more examples!

Guiding Principles

The more your tests resemble the way your software is used, the more confidence they can give you.

We try to only expose methods and utilities that encourage you to write tests that closely resemble how your Vue components are used.

Utilities are included in this project based on the following guiding principles:

  1. If it relates to rendering components, it deals with DOM nodes rather than component instances, nor should it encourage dealing with component instances.
  2. It should be generally useful for testing individual Vue components or full Vue applications.
  3. Utility implementations and APIs should be simple and flexible.

At the end of the day, what we want is for this library to be pretty light-weight, simple, and understandable.

Docs

Read the docs | Edit the docs

Typings

Please note that TypeScript 4.X is required.

The TypeScript type definitions are in the types directory.

ESLint support

If you want to lint test files that use Vue Testing Library, you can use the official plugin: eslint-plugin-testing-library.

Issues

Looking to contribute? Look for the Good First Issue label.

🐛 Bugs

Please file an issue for bugs, missing documentation, or unexpected behavior.

See Bugs

💡 Feature Requests

Please file an issue to suggest new features. Vote on feature requests by adding a 👍. This helps maintainers prioritize what to work on.

❓ Questions

For questions related to using the library, please visit a support community instead of filing an issue on GitHub.

License

MIT

Contributors

dfcook afontcu eunjae-lee tim-maguire samdelacruz ankitsinghaniyaz lindgr3n kentcdodds brennj makeupsomething mb200 Oluwasetemi cimbul alexkrolick edufarre SandraDml arnaublanche NoelDeMartin chiptus bennettdams mediafreakch afenton90 cilice ITenthusiasm