Copied to Clipboard
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 🖥️