DEV Community

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

Posted on

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

Top comments (0)