Nuxt 13 ๐ Testing & Nuxt DevTools โ Inspecting the Virtual File System (VFS) and writing unit/E2E tests with @nuxt/test-utils and Vitest
A Nuxt application is not just the files you write. Between your source code and the browser sits a generated virtual file system: hundreds of .d.ts files, a rewritten tsconfig.json, the compiled Nuxt config, route manifests, and type declarations injected by every module you install. When an auto-import fails, when a component silently resolves to the wrong file, or when a module’s types refuse to appear, the answer is usually inside that generated tree โ and most developers never look at it.
Nuxt DevTools exists to make that generated tree visible. Its Virtual Files tab renders the exact contents of .nuxt/ and tells you which module or layer produced each file. Once you can see what the build actually produced, debugging becomes inspection instead of guessing.
The other half of confidence is automated verification. Nuxt is notoriously hard to unit test because everything depends on Nuxt context: auto-imports, useNuxtApp(), useRoute(), $fetch, plugins, and async Suspense setup. @nuxt/test-utils solves this by booting a real Nuxt instance inside Vitest, giving components the same context they have in production. The same package also boots a real server โ and optionally a real browser โ for end-to-end tests.
This chapter covers three things: the DevTools Virtual Files inspector and what it reveals, unit testing with the @nuxt/test-utils/runtime environment including mountSuspended and mockNuxtImport, and end-to-end testing with @nuxt/test-utils/e2e including server assertions and Playwright-driven browser flows.
Key point: The DevTools Virtual Files tab shows the generated .nuxt/ build output so you can see exactly what Nuxt injected, and @nuxt/test-utils wraps Vitest in two modes โ a nuxt runtime environment for component unit tests with real Nuxt context, and an e2e setup that boots a real server and browser.
Why Testing and Nuxt DevTools exist
The auto-import opacity problem. Nuxt auto-imports composables, components, and utilities so you never write the import statement. That is excellent ergonomics and terrible debuggability, because the name you type and the file it resolves to are connected by a generator you cannot see. DevTools exposes the generated imports.d.ts and components.d.ts files so the resolution is inspectable rather than magical.
The virtual file system problem. Everything Nuxt generates lives in .nuxt/, and that directory is gitignored, regenerated on every build, and never opened by hand. But it contains the truth about your app: the plugin order, the route manifest, the type declarations contributed by each module. Without a viewer, a type error in a module you installed has no visible cause.
The Nuxt context problem. A Vue component that calls useNuxtApp(), useRoute(), or an auto-imported composable cannot be mounted with plain @vue/test-utils. The component throws because there is no Nuxt instance behind inject(). mountSuspended exists precisely to construct that context โ plugins, auto-imports, Suspense resolution โ before the component renders.
The async setup problem. Nuxt components frequently use top-level await in <script setup>. Vue renders these behind a Suspense boundary, so a synchronous mount() returns a placeholder instead of the rendered output. mountSuspended awaits the boundary so the test sees the resolved DOM, which is why it is async.
The “it works in dev” problem. A page that loads in development may return a 500 in production because of SSR-only code paths, middleware, or environment variables. End-to-end tests boot the built application rather than the dev server, so the failure appears in CI instead of on deploy day.
The mocking cost problem. Nuxt auto-imports are compile-time transformations; vi.mock('~/composables/useCurrency') does not intercept them because the import never existed in source. mockNuxtImport exists to patch the auto-import registry itself, which is the only place where the substitution will be honoured.
a. Nuxt DevTools and the Virtual File System
Nuxt DevTools is installed automatically in modern Nuxt versions and is controlled through the devtools key in nuxt.config.ts. It runs only in development and mounts a floating panel in the browser.
// nuxt.config.ts
export default defineNuxtConfig({
devtools: {
enabled: true, // show the floating DevTools panel in dev only
timeline: {
enabled: true // record hooks, network, and component events for the Timeline tab
}
}
})
The Virtual Files tab is the one worth knowing first. It renders the contents of the generated .nuxt/ directory, refreshed on every rebuild, and annotates each file with the module or layer that produced it.
// .nuxt/ โ the generated virtual file system (development and build output)
// .nuxt/components.d.ts every auto-imported component and its resolved path
// .nuxt/imports.d.ts every auto-imported composable and its source module
// .nuxt/types/plugins.d.ts types injected by plugins via `declare module '#app'`
// .nuxt/nuxt.d.ts global Nuxt types referenced from the root tsconfig
// .nuxt/tsconfig.json generated tsconfig containing all path aliases
// .nuxt/routes.mjs generated route manifest derived from pages/
Reading components.d.ts answers the most common Nuxt question in seconds: which file did MyButton actually resolve to when three layers all ship a button. Reading imports.d.ts answers the second: which module provided useCurrency, and is there a duplicate from a second layer that shadows it.
Beyond Virtual Files, the panel exposes tabs that map directly onto build concepts. Pages shows the resolved route tree with each page’s file path. Components lists every registered component and its source. Imports lists auto-imports grouped by the directory or module that supplied them. Modules shows installed modules with their setup timings, which is how you find the module adding three seconds to startup. Server Routes lists Nitro handlers. The Timeline records hooks and requests so you can correlate a slow page with the hook that delayed it.
b. Unit testing with the Nuxt runtime environment
@nuxt/test-utils ships a Vitest environment called nuxt. Inside it, test files get the same auto-imports your application has, plus Nuxt-aware mount helpers. You enable it globally through the config helper, or per file with a docblock comment.
// vitest.config.ts
import { defineVitestConfig } from '@nuxt/test-utils/config'
export default defineVitestConfig({
test: {
environment: 'nuxt', // boot a Nuxt instance for every test file
environmentOptions: {
nuxt: {
domEnvironment: 'happy-dom' // lighter DOM than jsdom; fine for component tests
}
}
}
})
The per-file alternative is a comment on the first line, which is useful when most of your suite is plain unit tests and only some files need Nuxt context.
// tests/components/PriceTag.nuxt.spec.ts
// @vitest-environment nuxt
import { mountSuspended } from '@nuxt/test-utils/runtime'
import { describe, it, expect } from 'vitest'
import PriceTag from '~/components/PriceTag.vue'
describe('PriceTag', () => {
it('renders the amount', async () => {
const wrapper = await mountSuspended(PriceTag, { props: { amount: 42 } })
expect(wrapper.text()).toContain('42')
})
})
mountSuspended differs from mount in three ways: it is async because it awaits the Suspense boundary, it installs a Nuxt app instance so inject() and plugins resolve, and it keeps auto-imports working. Its options mirror mount with props, slots, and global, and it returns a VueWrapper.
Auto-imports cannot be intercepted with vi.mock, because the import statement does not exist in source and vi.mock requires a specifier. The supported mechanism is mockNuxtImport, which is hoisted to the top of the file by the Vitest transform and rewrites the import registry before the component module is evaluated.
// tests/components/PriceTag.nuxt.spec.ts
import { mountSuspended, mockNuxtImport } from '@nuxt/test-utils/runtime'
// Replace the auto-imported useCurrency with a deterministic stub.
// The factory is hoisted, so it must not reference outer variables.
mockNuxtImport('useCurrency', () => {
return () => ({ format: (n: number) => `$${n}` }) // fixed formatter, no locale drift
})
Server calls from components go through $fetch or useFetch, and registerEndpoint installs an in-memory Nitro handler for the duration of the test so no network request leaves the process.
// tests/components/ProductList.nuxt.spec.ts
import { registerEndpoint, mountSuspended } from '@nuxt/test-utils/runtime'
registerEndpoint('/api/products', () => [ // in-memory Nitro handler
{ id: 1, name: 'Keyboard' },
{ id: 2, name: 'Mouse' }
])
For nested components that are irrelevant to the assertion, mockComponent swaps the implementation without touching the parent. This keeps a unit test focused on one component’s rendered output instead of dragging the whole tree through the Nuxt context.
// tests/components/Checkout.nuxt.spec.ts
import { mockComponent } from '@nuxt/test-utils/runtime'
mockComponent('AppChart', () => // replace a heavy chart component
defineComponent({ render: () => h('div', 'chart-stub') })
)
c. End-to-end testing with the e2e helpers
The @nuxt/test-utils/e2e entry point builds and boots an actual Nuxt application, then hands you $fetch, fetch, url, and โ when a browser is requested โ createPage. The setup call runs inside describe and completes before any test executes.
// tests/e2e/api.spec.ts
import { describe, it, expect } from 'vitest'
import { setup, $fetch } from '@nuxt/test-utils/e2e'
describe('product API', async () => {
// Builds and boots a real Nuxt server against the project root
await setup({ server: true, browser: false })
it('returns three products', async () => {
const products = await $fetch('/api/products') // real HTTP against the booted server
expect(products).toHaveLength(3)
})
})
Passing browser: true switches on the Playwright integration. createPage returns a Playwright Page already pointed at the running server, so you can use locators and role-based queries exactly as in a plain Playwright project.
// tests/e2e/checkout.spec.ts
import { describe, it, expect } from 'vitest'
import { setup, createPage } from '@nuxt/test-utils/e2e'
describe('checkout', async () => {
await setup({ browser: true }) // requires @playwright/test to be installed
it('shows the confirmation banner', async () => {
const page = await createPage('/checkout') // real browser, real rendering
await page.getByRole('button', { name: 'Pay' }).click()
await expect(page.getByText('Payment received')).toBeVisible()
})
})
The remaining options control the lifecycle. build: false reuses an existing .output to skip a rebuild; dev: true runs the dev server instead of a production build, which is faster but does not catch SSR-only regressions; port and host pin the listener; nuxtConfig deep-merges overrides for the test run; and setupTimeout extends the wait for large projects whose first build exceeds the default.
// tests/e2e/smoke.spec.ts
await setup({
build: false, // reuse a previous .output instead of rebuilding
port: 3001, // avoid clashing with a dev server on 3000
nuxtConfig: {
runtimeConfig: { apiSecret: 'test-only' } // override config for the test run only
},
setupTimeout: 120_000 // first build on CI can be slow
})
Browser mode is where the layer pays off. A unit test can prove that a component formats a price correctly; only a browser test proves that hydration matched, that the route middleware redirected, and that the cookie was set before the redirect completed.
Complete Example Session
// ============================================
// PART 1: VITEST CONFIG WITH THE NUXT ENVIRONMENT
// ============================================
// vitest.config.ts
import { defineVitestConfig } from '@nuxt/test-utils/config'
export default defineVitestConfig({
test: {
environment: 'nuxt', // every file gets Nuxt context
environmentOptions: {
nuxt: { domEnvironment: 'happy-dom' } // fast DOM for component tests
}
}
})
<!-- ============================================
PART 2: THE COMPONENT UNDER TEST
============================================ -->
<!-- components/PriceTag.vue -->
<template>
<span class="price">{{ currency.format(amount) }}</span>
</template>
<script setup lang="ts">
const props = defineProps<{ amount: number }>()
const currency = useCurrency() // auto-imported composable, no import statement
</script>
// ============================================
// PART 3: UNIT TEST WITH mountSuspended
// ============================================
import { mountSuspended } from '@nuxt/test-utils/runtime'
import { describe, it, expect } from 'vitest'
import PriceTag from '~/components/PriceTag.vue'
describe('PriceTag', () => {
it('renders the formatted amount', async () => {
const wrapper = await mountSuspended(PriceTag, { props: { amount: 42 } })
expect(wrapper.text()).toContain('$42') // stub formatter from Part 4
})
})
// ============================================
// PART 4: MOCKING AN AUTO-IMPORT
// ============================================
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
// Hoisted above the component import, so the stub wins over the real composable
mockNuxtImport('useCurrency', () => {
return () => ({ format: (n: number) => `$${n}` })
})
// ============================================
// PART 5: MOCKING A SERVER ENDPOINT
// ============================================
import { registerEndpoint } from '@nuxt/test-utils/runtime'
registerEndpoint('/api/products', () => [
{ id: 1, name: 'Keyboard' },
{ id: 2, name: 'Mouse' }
]) // no network leaves the process
// ============================================
// PART 6: REPLACING A HEAVY CHILD COMPONENT
// ============================================
import { mockComponent } from '@nuxt/test-utils/runtime'
import { defineComponent, h } from 'vue'
mockComponent('AppChart', () => // stub keeps the tree shallow
defineComponent({ render: () => h('div', 'chart-stub') })
)
// ============================================
// PART 7: E2E SERVER SETUP
// ============================================
import { setup, $fetch } from '@nuxt/test-utils/e2e'
describe('server', async () => {
await setup({ server: true }) // build + boot real Nuxt
it('serves products', async () => {
expect(await $fetch('/api/products')).toHaveLength(3)
})
})
// ============================================
// PART 8: E2E BROWSER TEST
// ============================================
import { setup, createPage } from '@nuxt/test-utils/e2e'
describe('nav', async () => {
await setup({ browser: true })
it('navigates to pricing', async () => {
const page = await createPage('/')
await page.getByRole('link', { name: 'Pricing' }).click()
await expect(page).toHaveURL(/\/pricing$/) // real client-side routing
})
})
// ============================================
// PART 9: DEVTOOLS AND VFS INSPECTION
// ============================================
// nuxt.config.ts
export default defineNuxtConfig({
devtools: { enabled: true, timeline: { enabled: true } }
})
// Then open the Virtual Files tab and read .nuxt/components.d.ts
// to confirm which file a shadowed component resolved to.
// ============================================
// PART 10: THE SCRIPTS
// ============================================
{
"scripts": {
"test": "vitest", // watch mode for local development
"test:unit": "vitest run --dir tests/unit",
"test:e2e": "vitest run --dir tests/e2e"
}
}
The ten parts moved from configuring the Nuxt Vitest environment, through a component and its three mocking strategies, into e2e server and browser suites, and finished with DevTools configuration and the scripts that keep the two suites separate.
Quick Reference
DevTools Tabs Worth Knowing
| Tab | What It Shows |
|---|---|
| Virtual Files | Contents of .nuxt/ and what produced each file |
| Components | Every registered component and its source path |
| Imports | Auto-imports grouped by source directory or module |
| Modules | Installed modules with setup timing |
| Pages | Resolved route tree with page file paths |
| Server Routes | Nitro handlers registered by the app |
| Timeline | Recorded hooks, requests, and component events |
Runtime Test Helpers
| Helper | Purpose |
|---|---|
mountSuspended | Mount a component with Nuxt context and awaited Suspense |
renderSuspended | Render for @testing-library/vue queries |
mockNuxtImport | Replace an auto-imported composable (hoisted) |
mockComponent | Replace a registered component globally |
registerEndpoint | Install an in-memory Nitro handler |
E2E Setup Options
| Option | Effect |
|---|---|
server | Boot a real Nuxt server |
browser | Enable Playwright and createPage |
build | Rebuild the app, or reuse .output |
dev | Run the dev server instead of a production build |
port / host | Pin the listener address |
nuxtConfig | Deep-merge config overrides for the run |
setupTimeout | Extend the build wait for slow machines |
Test Environment Activation
| Method | Scope |
|---|---|
environment: 'nuxt' in config | Every test file |
// @vitest-environment nuxt | One file |
environmentOptions.nuxt.domEnvironment | DOM implementation |
@nuxt/test-utils/e2e import | No environment needed |
Best Practices
โ Do This:
// Read .nuxt/components.d.ts when a component resolves wrong
openDevToolsTab('Virtual Files') // โ
// Await mountSuspended; it resolves the Suspense boundary
const wrapper = await mountSuspended(Comp) // โ
// Use mockNuxtImport for auto-imports, never vi.mock
mockNuxtImport('useCurrency', () => () => ({ format: f })) // โ
// Register endpoints instead of hitting the network
registerEndpoint('/api/products', () => [ ... ]) // โ
// Keep e2e in a separate directory and script
"test:e2e": "vitest run --dir tests/e2e" // โ
// Reuse builds in CI with build: false when the output exists
await setup({ build: false }) // โ
// Test SSR paths with a production build, not the dev server
await setup({ dev: false }) // โ
โ Don’t Do This:
// Mount a Nuxt component with plain @vue/test-utils mount()
mount(Comp) // throws: no Nuxt app to inject // โ
// Try to intercept auto-imports with vi.mock
vi.mock('~/composables/useCurrency') // never called // โ
// Reference outer variables inside a mockNuxtImport factory
mockNuxtImport('useX', () => () => outerVar) // hoisting error // โ
// Assert on async setup output before awaiting the mount
const w = mountSuspended(Comp); w.text() // placeholder only // โ
// Run browser e2e for coverage of pure functions
await setup({ browser: true }) // slow and unnecessary here // โ
// Leave .nuxt/ out of debugging entirely
// (it holds the answer to most resolution bugs) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
inject() only works in setup | Component mounted without Nuxt context | Use mountSuspended |
| Mock has no effect | vi.mock used on an auto-import | Use mockNuxtImport |
| Hoisting error in mock | Factory references outer variables | Inline the values in the factory |
| Empty rendered output | Async setup not awaited | await mountSuspended(...) |
| Component resolves to wrong file | Layer or module shadowing | Check .nuxt/components.d.ts |
| E2E port already in use | Dev server running on 3000 | Pass port: 3001 to setup |
| First e2e build times out | Cold build on CI | Raise setupTimeout |
$fetch fails in unit test | No Nitro handler registered | Use registerEndpoint |
Real-World Examples
1. Per-file Nuxt environment
// @vitest-environment nuxt
import { mountSuspended } from '@nuxt/test-utils/runtime'
2. Asserting on a formatted value
const wrapper = await mountSuspended(PriceTag, { props: { amount: 99 } })
expect(wrapper.text()).toContain('$99')
3. Stubbing a locale-dependent composable
mockNuxtImport('useLocalePath', () => (p: string) => `/en${p}`)
4. Endpoint that returns 404
registerEndpoint('/api/missing', () => { throw createError({ statusCode: 404 }) })
5. Stubbing a slot-heavy component
mockComponent('AppModal', () => defineComponent({ template: '<div><slot /></div>' }))
6. E2E asserting on a JSON route
await setup({ server: true })
expect(await $fetch('/api/health')).toEqual({ ok: true })
7. E2E asserting on server-rendered HTML
const html = await $fetch('/about') // built app, not the dev server
expect(html).toContain('About us')
8. Browser test with a role query
const page = await createPage('/login')
await page.getByLabel('Email').fill('a@b.c')
9. Overriding runtime config for the run
await setup({ nuxtConfig: { runtimeConfig: { token: 'test' } } })
10. Inspecting generated imports
// .nuxt/imports.d.ts โ confirms which module supplied useCurrency
Visual
The Testing Layers
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ BROWSER E2E Playwright drives a built app โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ SERVER E2E $fetch against a booted server โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ RUNTIME UNIT mountSuspended inside Nuxt context โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ PLAIN UNIT pure functions, no Nuxt at all โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Virtual File System
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SOURCE GENERATED (.nuxt/) โ
โ โ
โ components/*.vue โโโบ components.d.ts โ
โ composables/*.ts โโโบ imports.d.ts โ
โ plugins/*.ts โโโบ types/plugins.d.ts โ
โ nuxt.config.ts โโโบ nuxt.config.mjs โ
โ pages/*.vue โโโบ routes.mjs โ
โ โ
โ DevTools โบ Virtual Files renders every line above โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Why mountSuspended Is Async
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ <script setup> with top-level await โ
โ โ โ
โ โผ โ
โ Vue Suspense boundary โ
โ โ โ
โ โโโโโโโโดโโโโโโโโ โ
โ โผ โผ โ
โ mount() mountSuspended() โ
โ returns awaits boundary, returns โ
โ placeholder the resolved DOM โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Mock Resolution Order
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ mockNuxtImport factory โโโบ hoisted to file top โ
โ โ โ
โ โผ โ
โ auto-import registry patched โ
โ โ โ
โ โผ โ
โ component module evaluated โ
โ โ โ
โ โผ โ
โ useCurrency() resolves to the stub โ
โ โ
โ vi.mock() is never reached โ no specifier exists โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| DevTools config key | devtools.enabled |
| VFS location | .nuxt/ directory |
| Component declarations | .nuxt/components.d.ts |
| Auto-import declarations | .nuxt/imports.d.ts |
| Runtime mount helper | mountSuspended |
| Auto-import mock | mockNuxtImport |
| Endpoint mock | registerEndpoint |
| E2E boot | setup from @nuxt/test-utils/e2e |
| Browser driver | Playwright via createPage |
| Test environment name | nuxt |
Key takeaways:
- The Virtual Files tab makes generated code visible. Every auto-import and component registration is a line in
.nuxt/, and DevTools shows which module or layer produced it, which ends resolution guessing. mountSuspendedis the only correct mount for Nuxt components. It is async because it awaitsSuspense, and it installs the Nuxt app soinject(), plugins, and auto-imports all work.mockNuxtImportreplacesvi.mockfor auto-imports. Auto-imports have no specifier forvi.mockto intercept, so the registry itself must be patched, and the factory must be self-contained because it is hoisted.registerEndpointkeeps unit tests offline. It installs an in-memory Nitro handler, so$fetchanduseFetchresolve without a network round trip and without a running server.- E2E tests boot the built application.
setupcompiles and starts a real Nuxt server, andbrowser: trueadds Playwright for hydration, routing, and cookie assertions that unit tests cannot reach. - Separate the two suites. Unit tests belong in a fast watch loop with the
nuxtenvironment; e2e tests belong in CI with a production build and an explicit script.
Remember: Nuxt testing has two distinct questions to answer. The first is “what did the build actually produce,” and the answer is always in .nuxt/, rendered by the DevTools Virtual Files tab. The second is “does the application behave correctly,” and the answer comes from two Vitest environments โ the nuxt runtime for components that need real Nuxt context, and @nuxt/test-utils/e2e for a booted server and a real browser. Use the first to debug, the second to prevent regressions, and keep them in separate scripts so neither slows the other down.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!