0
0
Vueframework~5 mins

Vitest setup for unit testing in Vue

Choose your learning style9 modes available
Introduction

Vitest helps you check if your Vue code works correctly by running small tests automatically.

You want to make sure your Vue components behave as expected.
You need to catch bugs early before users see them.
You want to test functions or logic inside your Vue app.
You want to run tests quickly during development.
You want to keep your code reliable as it grows.
Syntax
Vue
npm install -D vitest @vue/test-utils

// vitest.config.ts
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'

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

Use npm install -D to add Vitest and Vue Test Utils as developer tools.

The config file tells Vitest to work with Vue and use a browser-like environment.

Examples
Installs Vitest and Vue Test Utils for writing and running tests.
Vue
npm install -D vitest @vue/test-utils
Basic Vitest config to enable Vue support and set test environment to simulate a browser.
Vue
// vitest.config.ts
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'

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

This example shows a simple Vue component and a Vitest test that checks if the message appears correctly.

Vue
// HelloWorld.vue
<template>
  <h1>{{ msg }}</h1>
</template>

<script setup>
const props = defineProps({ msg: String })
</script>

// HelloWorld.test.ts
import { mount } from '@vue/test-utils'
import { describe, it, expect } from 'vitest'
import HelloWorld from './HelloWorld.vue'

describe('HelloWorld', () => {
  it('shows the message', () => {
    const wrapper = mount(HelloWorld, { props: { msg: 'Hi there!' } })
    expect(wrapper.text()).toBe('Hi there!')
  })
})
OutputSuccess
Important Notes

Use globals: true in config to avoid importing test functions every time.

The jsdom environment simulates a browser so Vue components can be tested.

Run tests with npx vitest or add a script in package.json.

Summary

Vitest helps test Vue components easily with fast feedback.

Install Vitest and Vue Test Utils, then configure Vitest for Vue and jsdom.

Write tests to check component output and behavior.