Generating Vue 3 + Vite boilerplate with Vitest and MSW
The setup includes a minimal project with vite.config.ts configuring Vitest to use JSDOM and setup files for MSW. MSW handlers simulate delayed and error API responses, and the test suite initializes the MSW server lifecycle around tests. The example covers a UserList component fetching users with loading and error states, tested with Vitest using async utilities and MSW mocks. The sample package.json includes essential dependencies and test scripts for a ready-to-run environment.
Below is a minimal Vue 3 + Vite boilerplate wired up with Vitest (JSDOM) and MSW to mock API calls (including latency and error scenarios).
1) Project Structure
code Copy code
.
├─ package.json
├─ vite.config.ts
├─ tsconfig.json # optional but recommended
├─ src
│ ├─ main.ts
│ ├─ App.vue
│ ├─ api
│ │ └─ users.ts
│ └─ components
│ └─ UserList.vue
└─ tests
├─ setup.ts
├─ __mocks__
│ └─ handlers.ts
└─ UserList.spec.ts
2) package.json
json Copy code
{
"name": "vue3-vitest-msw-boilerplate",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "vitest run",
"test:ui": "vitest --ui",
"coverage": "vitest run --coverage"
},
"devDependencies": {
"@vitejs/plugin-vue": "^5.0.0",
"jsdom": "^24.0.0",
"msw": "^2.3.0",
"typescript": "^5.3.3",
"vite": "^5.0.0",
"vitest": "^1.3.0",
"vue": "^3.4.0",
"vue-tsc": "^1.8.0"
}
}
3) vite.config.ts
ts Copy code
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: './tests/setup.ts',
coverage: {
reporter: ['text', 'html']
}
}
})
4) tsconfig.json (optional)
json Copy code
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "Node",
"strict": true,
"jsx": "preserve",
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"lib": ["ESNext", "DOM"],
"types": ["vitest/globals", "vite/client"]
},
"include": ["src/**/*", "tests/**/*", "vite.config.ts"]
}
5) src/main.ts
ts Copy code
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
6) src/App.vue
vue Copy code
<template>
<main class="app">
<h1>Vue + Vitest + MSW Boilerplate</h1>
<UserList />
</main>
</template>
<script setup lang="ts">
import UserList from './components/UserList.vue'
</script>
<style scoped>
.app {
font-family: Avenir, Helvetica, Arial, sans-serif;
padding: 1rem;
}
</style>
7) src/api/users.ts
ts Copy code
export type User = { id: number; name: string }
export async function fetchUsers(): Promise<User[]> {
const res = await fetch('/api/users')
if (!res.ok) {
throw new Error(`Error fetching users: ${res.statusText}`)
}
return res.json()
}
8) src/components/UserList.vue
vue Copy code
<template>
<section>
<button data-testid="reload" @click="load" :disabled="loading">
{{ loading ? 'Loading…' : 'Reload' }}
</button>
<p v-if="error" class="error" data-testid="error">{{ error }}</p>
<ul v-else-if="users.length" data-testid="user-list">
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
<p v-else data-testid="empty">No users found.</p>
</section>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { fetchUsers, type User } from '../api/users'
const users = ref<User[]>([])
const loading = ref(false)
const error = ref('')
async function load() {
loading.value = true
error.value = ''
try {
users.value = await fetchUsers()
} catch (e: any) {
error.value = e?.message ?? 'Unknown error'
users.value = []
} finally {
loading.value = false
}
}
onMounted(load)
</script>
<style scoped>
.error {
color: red;
}
</style>
9) tests/mocks /handlers.ts (MSW handlers)
ts Copy code
import { http, HttpResponse, delay } from 'msw'
export const handlers = [
// Successful response with artificial latency
http.get('/api/users', async () => {
await delay(500) // simulate network latency
return HttpResponse.json([
{ id: 1, name: 'Ada Lovelace' },
{ id: 2, name: 'Alan Turing' }
])
}),
// Example error endpoint
http.get('/api/users-error', async () => {
await delay(300)
return HttpResponse.json(
{ message: 'Something went wrong' },
{ status: 500 }
)
})
]
10) tests/setup.ts (MSW test setup)
ts Copy code
import { afterAll, afterEach, beforeAll, vi } from 'vitest'
import { setupServer } from 'msw/node'
import { handlers } from './__mocks__/handlers'
// Set up MSW server with default handlers
export const server = setupServer(...handlers)
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
afterEach(() => {
server.resetHandlers()
vi.restoreAllMocks()
})
afterAll(() => server.close())
11) tests/UserList.spec.ts
ts Copy code
import { render, screen, waitFor } from '@testing-library/vue'
import UserList from '../src/components/UserList.vue'
import { server } from './setup'
import { http, HttpResponse } from 'msw'
describe('UserList', () => {
it('renders users after latency', async () => {
render(UserList)
// loading state
expect(screen.getByText(/loading/i)).toBeInTheDocument()
// wait for users to appear
const list = await screen.findByTestId('user-list')
expect(list).toBeInTheDocument()
expect(list.children.length).toBe(2)
})
it('handles server error', async () => {
// Override handler to force error
server.use(
http.get('/api/users', () =>
HttpResponse.json({ message: 'Forced error' }, { status: 500 })
)
)
render(UserList)
const errorMsg = await screen.findByTestId('error')
expect(errorMsg).toHaveTextContent(/forced error/i)
})
it('reload button triggers refetch', async () => {
render(UserList)
// initial load success
await screen.findByTestId('user-list')
const reloadBtn = screen.getByTestId('reload')
// Override handler to different data on reload
server.use(
http.get('/api/users', () =>
HttpResponse.json([{ id: 3, name: 'Grace Hopper' }])
)
)
reloadBtn.click()
await waitFor(() => {
expect(screen.getByTestId('user-list').children.length).toBe(1)
expect(screen.getByText(/grace hopper/i)).toBeInTheDocument()
})
})
})
Note: This uses @testing-library/vue. You can swap to @vue/test-utils if you prefer. Install accordingly:
bash Copy code
npm i -D @testing-library/vue
12) Install & Run
bash Copy code
# install deps
npm install
# or pnpm/yarn
# run dev
npm run dev
# run tests
npm test
# or open the Vitest UI
npm run test:ui
Highlights
Vitest is configured with environment: 'jsdom' and a global test setup file (tests/setup.ts).
MSW is initialized in tests to intercept /api/users calls, simulating network latency and returning mock data.
Error states are handled via server.use(...) in test cases to override handlers.
The component shows loading, success, and error states, giving you a pattern to extend.
You can extend handlers to cover more endpoints, latency ranges (delay()), and additional error codes.