Logo

dev-resources.site

for different kinds of informations.

Testing Vue components with Vitest

Published at
1/13/2025
Categories
vue
vite
vitest
testing
Author
jacobandrewsky
Categories
4 categories in total
vue
open
vite
open
vitest
open
testing
open
Author
14 person written this
jacobandrewsky
open
Testing Vue components with Vitest

Modern front-end development demands robust testing practices to ensure the reliability and maintainability of applications.

Thankfully, in Vue we can use an amazing tool powered by Vite - Vitest that allows us to test Vue components easily.

In this article, I will dive into how you can use Vitest to test Vue components.

Enjoy!

๐Ÿค” What is Vitest?

Vitest is a blazing-fast testing framework designed to work seamlessly with Vite, a modern build tool. Hereโ€™s why Vitest is a great choice for testing Vue components:

  1. Speed: Built on Vite, Vitest leverages its fast build times and hot module replacement (HMR).
  2. TypeScript Support: Vitest has out-of-the-box TypeScript support.
  3. Vue Integration: It works well with Vue Test Utils, the official testing library for Vue.
  4. Rich Feature Set: Vitest includes features like snapshot testing, mocking, and watch mode for streamlined development.

๐ŸŸข Testing Vue components with Vitest

To start, ensure you have a Vue project set up with Vite. Then, install Vitest and related libraries:

npm install --save-dev vitest @vue/test-utils vue
Enter fullscreen mode Exit fullscreen mode

Add a vitest.config.ts file to configure Vitest:

import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom', // Simulates a browser environment
    setupFiles: './vitest.setup.ts', // Optional setup file
  },
});
Enter fullscreen mode Exit fullscreen mode

If you need to perform global configurations (e.g., mocking global variables), create a vitest.setup.ts file:

import { expect } from 'vitest';
import matchers from '@testing-library/jest-dom/matchers';

expect.extend(matchers);
Enter fullscreen mode Exit fullscreen mode

Letโ€™s write a simple test for a Vue component. Consider the following HelloWorld.vue component:

<template>
  <div>
    <h1>{{ message }}</h1>
    <button @click="updateMessage">Click Me</button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

const message = ref('Hello, Vue!')

function updateMessage() {
  message.value = 'You clicked the button!'
}
</script>
Enter fullscreen mode Exit fullscreen mode

Create a HelloWorld.spec.ts file in the tests directory:

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

describe('HelloWorld.vue', () => {
  it('renders the correct message', () => {
    const wrapper = mount(HelloWorld);
    expect(wrapper.text()).toContain('Hello, Vue!');
  });

  it('updates the message when the button is clicked', async () => {
    const wrapper = mount(HelloWorld);
    await wrapper.find('button').trigger('click');
    expect(wrapper.text()).toContain('You clicked the button!');
  });
});
Enter fullscreen mode Exit fullscreen mode

Run your tests using the following command:

npx vitest
Enter fullscreen mode Exit fullscreen mode

For a more interactive experience, you can use watch mode:

npx vitest --watch
Enter fullscreen mode Exit fullscreen mode

๐Ÿ™‹ Bonus - additional testing techniques

Snapshot testing captures a rendered componentโ€™s output and compares it to a baseline. Add a snapshot test to the HelloWorld.spec.ts:

it('matches the snapshot', () => {
  const wrapper = mount(HelloWorld);
  expect(wrapper.html()).toMatchSnapshot();
});
Enter fullscreen mode Exit fullscreen mode

Vitest allows you to mock modules and functions. For instance:

vi.mock('axios', () => ({
  default: {
    get: vi.fn(() => Promise.resolve({ data: 'Mocked Data' }))
  }
}));
Enter fullscreen mode Exit fullscreen mode

Test how components handle props and emit events:

it('renders with props', () => {
  const wrapper = mount(HelloWorld, {
    props: { initialMessage: 'Hello, Props!' }
  });
  expect(wrapper.text()).toContain('Hello, Props!');
});
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“– Learn more

If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this link or by clicking the image below:

Vue School Link

It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects ๐Ÿ˜‰

โœ… Summary

Well done! Testing Vue components with Vitest is a straightforward and enjoyable process. Its speed, modern features, and seamless Vue integration make it an excellent choice for developers looking to ensure their applications are robust and maintainable.

Take care and see you next time!

And happy coding as always ๐Ÿ–ฅ๏ธ

vue Article's
30 articles in total
Favicon
Learning Vue
Favicon
Resolving Auto-Scroll issues for overflow container in a Nuxt app
Favicon
Building a new Chat
Favicon
Creating a scalable Monorepo for Vue - Workspaces
Favicon
Creating a scalable Monorepo for Vue - Intro
Favicon
How to Load Remote Components in Vue 3
Favicon
Middlewares: O que sรฃo e como utilizar no Nuxt.JS
Favicon
Sore Throat: Causes, Symptoms, and Treatment
Favicon
Transform Your Web Development Workflow with These JavaScript Giants
Favicon
Integrate Storybook with VueJS
Favicon
Why JSX/TSX Isn't Cool
Favicon
We released AdminForth Components Library
Favicon
JSON Visual Edit
Favicon
How to create perfect CSS circle sectors
Favicon
Shady QR Code Generator Pages? Ugh!
Favicon
I Built a CaddyFile Generator Tool in Just 8 Hours โ€“ Hereโ€™s How It Went
Favicon
How to setup VueJs in Neovim (January 2025)
Favicon
Corello, Simple Dtos in FrontEnd
Favicon
The easiest way to migrate from Nuxt 3 to Nuxt 4!
Favicon
Vike - Next.js & Nuxt alternative for unprecedented flexibility and dependability
Favicon
Creating a Scroll-Spy Menu with Nuxt 3 and Intersection Observer API
Favicon
vue project
Favicon
Vue.js Fetch API | Search Vue.js | Sort Vue.js | Pagination Vue.js | Filter Vue.js
Favicon
[Boost]
Favicon
Testing Vue components with Vitest
Favicon
How can VoidZero be commercialized?
Favicon
romantic-cannon-lpg3yr
Favicon
Building a Vue CRUD App with a Spring Boot API
Favicon
Vue 3 Slowly Turning Into React? (I'm Honestly confused.)
Favicon
Angular vs. React vs. Vue

Featured ones: