Testing your Add-on
In this guide you will set up and use Vitest in a Vue Single Page Application (SPA) to test components and services. Specifically, you will learn how to mock an external API called MyCustomBackendAPI
, which retrieves permissions for the current user. We will be using the vi
helper from Vitest to handle the mocking.
Prerequisites
- Node.js and npm installed
- A Vue 3 project set up with Vite
- Vitest installed and configured in your project
Installing Vitest
If you haven’t already installed Vitest, you can do so by running:
npm install vitest --save-dev
Configuring Vitest in a Vue project
Ensure that your vite.config.js
file includes the necessary configuration for Vitest:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { configDefaults } from 'vitest/config'
export default defineConfig({
plugins: [vue()],
test: {
globals: true,
environment: 'jsdom',
setupFiles: './tests/setup.js', // Optional setup file for initializing tests
coverage: {
reporter: ['text', 'json', 'html'],
},
exclude: [...configDefaults.exclude, 'e2e/*'],
},
})
Setting up a backend service
Assume you have a service that interacts with an external API to fetch permissions for the current user. Here's a simple example of what MyCustomBackendAPI.js
might look like:
// src/services/MyCustomBackendAPI.js
import axios from 'axios';
export default {
getUserPermissions() {
return axios.get('/api/permissions');
}
}
Writing a Component that Uses MyCustomBackendAPI
Here's an example of a Vue component that uses the MyCustomBackendAPI
service:
<template>
<div v-if="permissions">
<p>User Permissions:</p>
<ul>
<li v-for="permission in permissions" :key="permission">{{ permission }}</li>
</ul>
</div>
</template>
<script setup>
import MyCustomBackendAPI from '@/services/MyCustomBackendAPI';
const permissions = ref(null);
const fetchPermissions = async () => {
permissions.value = await MyCustomBackendAPI.getUserPermissions();
}
onMounted(() => {
fetchPermissions();
});
</script>
Setting up tests with Vitest
Installing necessary test utilities
To write and run tests, install the following utility packages:
npm install @vue/test-utils @testing-library/jest-dom --save-dev
Writing a test with Vitest and mocking MyCustomBackendAPI
Let's write a test for our Vue component, ensuring that we mock the MyCustomBackendAPI
to avoid actual HTTP requests during the test:
// tests/components/UserPermissions.spec.js
import { mount } from '@vue/test-utils';
import { describe, it, expect, vi } from 'vitest';
import UserPermissions from '@/components/UserPermissions.vue';
import MyCustomBackendAPI from '@/services/MyCustomBackendAPI';
describe('UserPermissions.vue', () => {
it('renders user permissions from API', async () => {
// Mock the MyCustomBackendAPI.getUserPermissions method
const mockPermissions = ['read', 'write', 'execute'];
vi.spyOn(MyCustomBackendAPI, 'getUserPermissions').mockResolvedValue(mockPermissions);
// Mount the component
const wrapper = mount(UserPermissions);
// Wait for the component to load data
await wrapper.vm.$nextTick();
// Check that the correct data was rendered
expect(wrapper.findAll('li').length).toBe(mockPermissions.length);
expect(wrapper.text()).toContain('read');
expect(wrapper.text()).toContain('write');
expect(wrapper.text()).toContain('execute');
});
it('handles API failure', async () => {
// Mock the MyCustomBackendAPI.getUserPermissions method to reject
vi.spyOn(MyCustomBackendAPI, 'getUserPermissions').mockRejectedValue(new Error('API error'));
// Mount the component
const wrapper = mount(UserPermissions);
// Wait for the component to handle the error
await wrapper.vm.$nextTick();
// Check that no permissions are rendered
expect(wrapper.findAll('li').length).toBe(0);
expect(wrapper.text()).not.toContain('User Permissions');
});
});
Explanation of the test code
vi.spyOn
: This Vitest helper is used to mockMyCustomBackendAPI.getUserPermissions
so that it returns a controlled response without making an actual HTTP request.mockResolvedValue
: Simulates a successful API response.mockRejectedValue
: Simulates an API failure scenario.mount
: Provided by@vue/test-utils
, this function mounts the Vue component in a test environment.await wrapper.vm.$nextTick()
: Ensures that the component has finished processing any asynchronous actions before assertions are made.- Assertions: Checks if the permissions are correctly rendered based on the mocked API response.
Running the Tests
To run your tests using Vitest, simply execute:
npx vitest
You can also run tests in watch mode with:
npx vitest --watch