</>
Skip to content
Vue lessons (35/43)

Vue — Testing

Setup Vitest

npm install -D vitest @vue/test-utils jsdom

vitest.config.js:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  test: {
    environment: 'jsdom'
  }
})

Basic test

// Counter.spec.js
import { mount } from '@vue/test-utils'
import Counter from './Counter.vue'

describe('Counter', () => {
  it('renders correctly', () => {
    const wrapper = mount(Counter)
    expect(wrapper.text()).toContain('Count: 0')
  })

  it('increments on click', async () => {
    const wrapper = mount(Counter)
    await wrapper.find('button').trigger('click')
    expect(wrapper.text()).toContain('Count: 1')
  })
})

Testing props

it('renders title prop', () => {
  const wrapper = mount(Counter, {
    props: { title: 'My Counter' }
  })
  expect(wrapper.text()).toContain('My Counter')
})

Testing events

it('emits increment event', async () => {
  const wrapper = mount(Counter)
  await wrapper.find('button').trigger('click')
  expect(wrapper.emitted('increment')).toBeTruthy()
})

E2E with Cypress

npm install -D cypress
// cypress/e2e/spec.cy.js
describe('My App', () => {
  it('loads the page', () => {
    cy.visit('/')
    cy.contains('Hello Vue!')
  })

  it('clicks the button', () => {
    cy.visit('/')
    cy.get('button').click()
    cy.contains('Count: 1')
  })
})

Run tests

# Unit tests
npm run test:unit

# E2E tests
npm run test:e2e

Mini Practice

  1. Set up Vitest for unit testing
  2. Write tests for a component
  3. Test props and events
  4. Add an E2E test with Cypress

Up Next

Continue with TypeScript - TypeScript support.

Related Topics

Frequently Asked Questions about Testing

What is Testing in Vue?

Testing is a fundamental concept in Vue. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Testing?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Testing.

Why is Testing important in Vue?

Testing is essential for Vue development. Understanding this concept will help you write better code and solve real-world problems more effectively.