DEV Community

Cover image for Testing Vue components with Vitest
Jakub Andrzejewski
Jakub Andrzejewski

Posted on

22 1 1 1 1

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 🖥️

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (4)

Collapse
 
hinogi profile image
Stefan Schneider

Also, you can use Storybook to develop you component and either use play to add some tests or and/or use Portable stories to add 'unit' tests on top of them or just run them with a test runner.
The current experimental test util makes it even better.

Collapse
 
hinogi profile image
Stefan Schneider

Also @basarbk has an excellent udemy course udemy.com/course/vue-with-test-dri...
In that he has some smart helper for rendering github.com/basarbk/tdd-vue3/blob/m... that adds to the beauty of using testing-library/vue instead of plain vue-test-utils :D

Collapse
 
userquin profile image
userquin

Test also your Vue components in the actual browser: vitest.dev/guide/browser.html ;)

Collapse
 
sanjeetsingh profile image
Sanjeet Singh

very informative thanks for sharing

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay