vue-testing-library
🦎 Simple and complete Vue.js testing utilities that encourage good testing practices.
Top Related Projects
Vue Test Utils for Vue 3
Fast, easy and reliable testing for anything that runs in a browser.
Next generation testing framework powered by Vite.
Additional Jest matchers 🃏💪
Quick Overview
Vue Testing Library is a lightweight solution for testing Vue components. It provides utility functions to interact with Vue components in a way that resembles how users would use them, encouraging better testing practices and more maintainable tests.
Pros
- Encourages writing tests that focus on component behavior rather than implementation details
- Provides a simple and intuitive API for querying and interacting with components
- Compatible with various test runners and assertion libraries
- Supports both Vue 2 and Vue 3
Cons
- May require a mindset shift for developers accustomed to testing implementation details
- Limited support for testing certain advanced Vue features or complex component interactions
- Learning curve for developers new to the "Testing Library" philosophy
- Slightly more verbose setup compared to Vue's built-in test utils
Code Examples
- Rendering a component and querying elements:
import { render, screen } from '@testing-library/vue'
import MyComponent from './MyComponent.vue'
test('renders greeting', () => {
render(MyComponent, { props: { name: 'World' } })
expect(screen.getByText('Hello, World!')).toBeInTheDocument()
})
- Simulating user interactions:
import { render, fireEvent } from '@testing-library/vue'
import Counter from './Counter.vue'
test('increments counter on button click', async () => {
const { getByText } = render(Counter)
const button = getByText('Increment')
await fireEvent.click(button)
expect(getByText('Count: 1')).toBeInTheDocument()
})
- Testing asynchronous behavior:
import { render, waitFor } from '@testing-library/vue'
import AsyncComponent from './AsyncComponent.vue'
test('loads data asynchronously', async () => {
const { getByText } = render(AsyncComponent)
await waitFor(() => {
expect(getByText('Data loaded!')).toBeInTheDocument()
})
})
Getting Started
-
Install the library:
npm install --save-dev @testing-library/vue
-
Set up your test file:
import { render, screen } from '@testing-library/vue' import MyComponent from './MyComponent.vue' test('component renders correctly', () => { render(MyComponent) expect(screen.getByText('Hello, Vue!')).toBeInTheDocument() })
-
Run your tests using your preferred test runner (e.g., Jest, Vitest).
Competitor Comparisons
Vue Test Utils for Vue 3
Pros of test-utils
- More comprehensive API with direct access to Vue internals
- Tighter integration with Vue ecosystem and tooling
- Supports advanced testing scenarios like shallow rendering
Cons of test-utils
- Steeper learning curve due to more complex API
- May encourage testing implementation details rather than user behavior
- Requires more setup and boilerplate code for basic tests
Code Comparison
test-utils:
import { mount } from '@vue/test-utils'
import Component from './Component.vue'
test('Component renders correctly', () => {
const wrapper = mount(Component)
expect(wrapper.find('.class-name').exists()).toBe(true)
})
vue-testing-library:
import { render } from '@testing-library/vue'
import Component from './Component.vue'
test('Component renders correctly', () => {
const { getByTestId } = render(Component)
expect(getByTestId('element-id')).toBeInTheDocument()
})
Key Differences
- Philosophy: test-utils focuses on component internals, while vue-testing-library emphasizes testing from a user's perspective.
- API: test-utils provides a more extensive API, while vue-testing-library offers a simpler, more focused set of utilities.
- Learning curve: test-utils may require more time to master, whereas vue-testing-library is designed for quick adoption and ease of use.
- Testing approach: test-utils allows for more granular testing of component logic, while vue-testing-library encourages testing component behavior and accessibility.
Fast, easy and reliable testing for anything that runs in a browser.
Pros of Cypress
- End-to-end testing framework with a rich set of features for real browser testing
- Intuitive, interactive test runner with time-travel debugging
- Automatic waiting and retry mechanisms for more stable tests
Cons of Cypress
- Limited cross-browser support compared to Vue Testing Library
- Steeper learning curve due to its comprehensive feature set
- Can be slower for unit and integration tests
Code Comparison
Vue Testing Library:
import { render, fireEvent } from '@testing-library/vue'
import MyComponent from './MyComponent.vue'
test('increments counter on button click', async () => {
const { getByText } = render(MyComponent)
await fireEvent.click(getByText('Increment'))
expect(getByText('Count: 1')).toBeTruthy()
})
Cypress:
describe('MyComponent', () => {
it('increments counter on button click', () => {
cy.mount(MyComponent)
cy.contains('Increment').click()
cy.contains('Count: 1').should('exist')
})
})
Vue Testing Library focuses on testing components in isolation, promoting accessibility and best practices. It's lightweight and easy to set up. Cypress, on the other hand, excels in end-to-end testing, providing a more comprehensive testing environment with powerful debugging tools. While Cypress can be used for component testing, it's primarily designed for full application testing scenarios.
Next generation testing framework powered by Vite.
Pros of Vitest
- Faster test execution due to native ESM support and parallelization
- Built-in TypeScript support without additional configuration
- Seamless integration with Vite for a unified development experience
Cons of Vitest
- Less mature ecosystem compared to Jest-based solutions
- May require additional setup for certain Vue-specific testing scenarios
- Limited browser environment support (primarily Node.js focused)
Code Comparison
Vue Testing Library:
import { render, fireEvent } from '@testing-library/vue'
import MyComponent from './MyComponent.vue'
test('increments counter on button click', async () => {
const { getByText } = render(MyComponent)
await fireEvent.click(getByText('Increment'))
expect(getByText('Count: 1')).toBeTruthy()
})
Vitest:
import { mount } from '@vue/test-utils'
import { expect, test } from 'vitest'
import MyComponent from './MyComponent.vue'
test('increments counter on button click', async () => {
const wrapper = mount(MyComponent)
await wrapper.find('button').trigger('click')
expect(wrapper.text()).toContain('Count: 1')
})
Both libraries offer ways to test Vue components, but Vue Testing Library focuses on testing from a user's perspective, while Vitest provides a more flexible approach with Vue Test Utils integration.
Additional Jest matchers 🃏💪
Pros of jest-extended
- Provides a wide range of additional matchers for Jest, enhancing test expressiveness
- Can be used with any JavaScript project using Jest, not limited to Vue applications
- Offers more specific assertions for various data types and scenarios
Cons of jest-extended
- Requires additional setup and configuration compared to vue-testing-library
- May introduce a learning curve for developers unfamiliar with the extended matchers
- Doesn't provide Vue-specific utilities or rendering capabilities
Code Comparison
vue-testing-library:
import { render, fireEvent } from '@testing-library/vue'
import MyComponent from './MyComponent.vue'
test('increments counter on button click', async () => {
const { getByText } = render(MyComponent)
await fireEvent.click(getByText('Increment'))
expect(getByText('Count: 1')).toBeTruthy()
})
jest-extended:
import 'jest-extended'
test('array contains specific items', () => {
expect([1, 2, 3]).toIncludeSameMembers([3, 1, 2])
expect([{ a: 1 }, { b: 2 }]).toSatisfyAll(item => item instanceof Object)
})
While vue-testing-library focuses on rendering and interacting with Vue components, jest-extended enhances Jest's assertion capabilities for various data types and scenarios, not specific to Vue or any framework.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Vue Testing Library
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.
Table of Contents
- Installation
- A basic example
- Guiding Principles
- Docs
- Typings
- ESLint support
- Issues
- License
- Contributors
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 writeexpect(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:
- If it relates to rendering components, it deals with DOM nodes rather than component instances, nor should it encourage dealing with component instances.
- It should be generally useful for testing individual Vue components or full Vue applications.
- 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
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.
ð¡ 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
Contributors
Top Related Projects
Vue Test Utils for Vue 3
Fast, easy and reliable testing for anything that runs in a browser.
Next generation testing framework powered by Vite.
Additional Jest matchers 🃏💪
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot