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
Jakub Andrzejewski
Categories
4 categories in total
vue
open
vite
open
vitest
open
testing
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

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
  },
});

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);

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>

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!');
  });
});

Run your tests using the following command:

npx vitest

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

npx vitest --watch

๐Ÿ™‹ 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();
});

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

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

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!');
});

๐Ÿ“– 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 ๐Ÿ–ฅ๏ธ

Featured ones: