### Complete Vitest Browser Vue Setup
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/configuration.md
A complete setup example for vitest.config.ts and test/setup.ts, including Vue plugins, router, i18n, and mocks.
```typescript
// vitest.config.ts
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
import { playwright } from '@vitest/browser-playwright'
import { createRouter, createMemoryHistory } from 'vue-router'
import { createI18n } from 'vue-i18n'
export default defineConfig({
plugins: [vue()],
test: {
setupFiles: ['vitest-browser-vue'],
browser: {
enabled: true,
provider: playwright(),
headless: true,
},
},
})
// test/setup.ts (referenced in setupFiles if needed)
import { config } from 'vitest-browser-vue'
const i18n = createI18n({
locale: 'en',
messages: {
en: { hello: 'Hello' },
},
})
const router = createRouter({
history: createMemoryHistory(),
routes: [],
})
config.global.plugins = [i18n, router]
config.global.mocks = {
$analytics: {
track: () => {},
},
}
config.global.stubs = {
Teleport: false,
}
```
--------------------------------
### Vitest Browser Vue Render Examples
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/types.md
Demonstrates various ways to use the `render` function with different options, including minimal setup, props, slots, custom containers, and global configurations. Ensure necessary imports are present.
```typescript
import { render } from 'vitest-browser-vue'
import MyComponent from './MyComponent.vue'
// Minimal options
const screen1 = await render(MyComponent)
// With props
const screen2 = await render(MyComponent, {
props: { id: '123', disabled: false }
})
// With slots
const screen3 = await render(MyComponent, {
slots: {
default: '
(Component, options?) => RenderResult & PromiseLike>`): Mount a Vue component (no auto-cleanup).
- **cleanup** (`() => void`): Manually unmount all rendered components.
### Re-exports
- **config** (`@vue/test-utils`): Global test configuration object.
### Type Exports
- **RenderResult** (`Props`): Return type of render().
- **ComponentRenderOptions** (`C, P`): Options for render().
### No Side Effects
- Does NOT register `beforeEach` cleanup hook.
- Does NOT extend the `page` object.
- Does NOT declare TypeScript module augmentation.
```
--------------------------------
### Automatic Cleanup Example
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/api-reference/page-methods.md
Demonstrates how components rendered with page.render() are automatically cleaned up after each test when vitest-browser-vue is used as a setup file. No manual cleanup is required.
```typescript
import { page } from 'vitest/browser'
test('first test', async () => {
await page.render(Counter)
// Components are visible in the browser UI
// cleanup() is called after this test runs
})
test('second test', async () => {
// DOM is clean from the first test
await page.render(Counter)
})
```
--------------------------------
### Vitest Configuration for Setup Files
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/api-reference/page-methods.md
Configures Vitest to use 'vitest-browser-vue' as a setup file. This enables the extended page object with render and automatic cleanup features.
```typescript
test: {
setupFiles: ['vitest-browser-vue'],
}
```
--------------------------------
### Install Global Plugins
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/api-reference/config.md
Install global Vue plugins such as Vue Router or Pinia. This makes the plugin's functionality available to all components rendered during the test.
```typescript
import { config } from 'vitest-browser-vue'
import { createI18n } from 'vue-i18n'
import { createRouter, createMemoryHistory } from 'vue-router'
const i18n = createI18n({
locale: 'en',
messages: {
en: { hello: 'Hello' }
}
})
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/', component: { template: 'Home
' } }
]
})
config.global.plugins = [i18n, router]
test('component using plugins', async () => {
const screen = await render(MyComponent)
// MyComponent can access i18n and router
})
```
--------------------------------
### Unmount Method Example
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/types.md
Example of using the unmount method to remove a rendered component and verify its removal.
```typescript
const screen = await render(MyComponent)
await screen.unmount()
expect(screen.container.innerHTML).toBe('')
```
--------------------------------
### Main Entry Side Effects and Setup
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/module-structure.md
Demonstrates how importing the main entry point automatically registers cleanup hooks, extends the page object, and declares TypeScript module augmentations.
```typescript
// Registered via beforeEach hook
beforeEach(() => {
cleanup()
})
// Page object extended with render method
page.extend({
render,
[Symbol.for('vitest:component-cleanup')]: cleanup,
})
// TypeScript module augmentation
declare module 'vitest/browser' {
interface BrowserPage {
render: typeof render
}
}
```
--------------------------------
### Rerender Method Example
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/types.md
Example showing how to use the rerender method to update a component's props and verify the updated state.
```typescript
const screen = await render(Counter, { props: { count: 0 } })
await expect.element(screen.getByText('Count is 0')).toBeVisible()
await screen.rerender({ count: 5 })
await expect.element(screen.getByText('Count is 5')).toBeVisible()
```
--------------------------------
### Configure Vitest for Browser Testing
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/INDEX.md
Set up Vitest to enable browser testing by specifying the setup file and enabling the browser option in the configuration.
```typescript
// vitest.config.ts
export default defineConfig({
test: {
setupFiles: ['vitest-browser-vue'],
browser: { enabled: true }
}
})
```
--------------------------------
### Slots Configuration Examples
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/configuration.md
Render slots with various content types, including strings, component templates, and scoped slots using functions that return template and data.
```typescript
// String slots
const screen1 = await render(MyComponent, {
slots: {
default: 'Default slot
',
header: 'Header
',
},
})
// Component slots
const screen2 = await render(MyComponent, {
slots: {
default: { template: 'Slot from template
' },
header: HeaderComponent,
},
})
// Scoped slots
const screen3 = await render(MyComponent, {
slots: {
default: (slotProps) => {
return {
template: `{{ count }}
`,
data: () => ({ count: slotProps.count }),
}
},
},
})
```
--------------------------------
### Install Vue Plugins Globally
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/configuration.md
Install Vue plugins globally for all tests. This allows components to use plugin APIs like useRoute() and useStore().
```typescript
import { config } from 'vitest-browser-vue'
import { createRouter, createMemoryHistory } from 'vue-router'
import { createPinia } from 'pinia'
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/', component: { template: 'Home
' } },
],
})
const pinia = createPinia()
config.global.plugins = [router, pinia]
```
--------------------------------
### Global Configuration Example
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/README.md
Apply global configurations such as mocks, stubs, or plugins to the testing environment. These settings affect all tests run with vitest-browser-vue.
```typescript
import { config } from 'vitest-browser-vue'
config.global.mocks = { $t: (k) => k }
config.global.stubs = { HeavyComponent: true }
config.global.plugins = [router, store]
```
--------------------------------
### Global Setup for Vitest Browser Vue
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/advanced-patterns.md
Configure Vitest plugins, mocks, and stubs globally in a setup file referenced in `vitest.config.ts`. These settings apply to all tests.
```typescript
// vitest.config.ts
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
test: {
setupFiles: ['vitest-browser-vue', './test/setup.ts'],
browser: { enabled: true },
},
})
// test/setup.ts
import { config } from 'vitest-browser-vue'
import router from './router'
import i18n from './i18n'
// These apply to all render() calls
config.global.plugins = [router, i18n]
config.global.mocks = {
$analytics: {
track: () => {},
},
}
config.global.stubs = {
Teleport: false,
AsyncComponent: { template: 'Async
' },
}
```
--------------------------------
### Manual Cleanup with Pure Import
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/api-reference/cleanup.md
Shows how to manually call cleanup() when importing from 'vitest-browser-vue/pure'. This is useful when automatic setup hooks are disabled.
```typescript
import { render, cleanup } from 'vitest-browser-vue/pure'
import { test } from 'vitest'
import MyComponent from './MyComponent.vue'
test('manual cleanup example', async () => {
const screen = await render(MyComponent)
// Test logic here
cleanup() // Manually clean up all rendered components
})
```
--------------------------------
### Basic Component Rendering
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/api-reference/render.md
Renders a Vue component and asserts its visibility. Ensure the component and testing utilities are imported correctly. This example demonstrates a basic usage pattern for rendering and verifying content.
```typescript
import { render } from 'vitest-browser-vue'
import { expect, test } from 'vitest'
import HelloWorld from './HelloWorld.vue'
test('renders hello world', async () => {
const screen = await render(HelloWorld)
await expect.element(screen.getByText('Hello World')).toBeVisible()
})
```
--------------------------------
### Debug Method Example
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/types.md
Example of using the debug method to print the entire DOM tree or a specific element.
```typescript
const screen = await render(MyComponent)
screen.debug() // Print entire tree
screen.debug(screen.getByRole('button')) // Print just the button
```
--------------------------------
### Browser Page Object Import
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/README.md
Imports the page object from vitest/browser when using it as a setup file.
```typescript
// Browser page object (when used as setup file)
import { page } from 'vitest/browser'
const screen = await page.render(Component)
```
--------------------------------
### Emitted Method Example
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/types.md
Example demonstrating how to use the emitted method to capture and assert on emitted events from a component.
```typescript
const screen = await render(ButtonComponent)
await screen.getByRole('button').click()
const clicks = screen.emitted('click')
expect(clicks).toHaveLength(1)
expect(clicks[0]).toEqual([])
```
--------------------------------
### Import Main Entry
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/README.md
Import necessary functions from the main entry point of vitest-browser-vue. This setup automatically handles cleanup and extends the page object.
```typescript
import { render, cleanup, config } from 'vitest-browser-vue'
```
--------------------------------
### Pure Entry Imports
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/module-structure.md
Imports core functions and types from the pure entry point of vitest-browser-vue, which avoids automatic setup.
```typescript
import { render, cleanup, config } from 'vitest-browser-vue/pure'
import type { RenderResult, ComponentRenderOptions } from 'vitest-browser-vue/pure'
```
--------------------------------
### Automatic Cleanup Example
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/api-reference/cleanup.md
Demonstrates how cleanup() is automatically called after each test when vitest-browser-vue is imported directly. No manual intervention is needed.
```typescript
import { render } from 'vitest-browser-vue'
import { test } from 'vitest'
import Counter from './Counter.vue'
test('first test', async () => {
const screen = await render(Counter)
// Test logic here
// cleanup() is called automatically after this test
})
test('second test', async () => {
// DOM is clean, no remnants from the first test
const screen = await render(Counter)
// Test logic here
})
```
--------------------------------
### Configure Global Mocks for Vue Components
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/README.md
Sets global configuration options, such as mocks, for Vue components tested with vitest-browser-vue. This example configures a mock for the $t function.
```javascript
import { config } from 'vitest-browser-vue'
config.global.mocks = {
$t: text => text
}
```
--------------------------------
### Reusable Test Fixtures with Routers and i18n
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/advanced-patterns.md
Create helper functions to encapsulate common rendering patterns, such as integrating Vue Router or i18n, to simplify test setup.
```typescript
import { render as baseRender } from 'vitest-browser-vue'
import { createRouter, createMemoryHistory } from 'vue-router'
import type { RenderResult } from 'vitest-browser-vue'
function renderWithRouter(component, routes = []) {
const router = createRouter({
history: createMemoryHistory(),
routes,
})
return baseRender(component, {
global: { plugins: [router] }
})
}
function renderWithI18n(component, messages = {}) {
const i18n = createI18n({ locale: 'en', messages })
return baseRender(component, {
global: { plugins: [i18n] }
})
}
// Usage
test('component with routing', async () => {
const screen = await renderWithRouter(MyComponent, [
{ path: '/', component: Home },
])
})
test('component with i18n', async () => {
const screen = await renderWithI18n(MyComponent, {
en: { hello: 'Hello' }
})
})
```
--------------------------------
### Vitest Configuration for Browser Mode
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/README.md
Configure Vitest to enable browser mode and specify the provider. This setup file enables auto-cleanup for vitest-browser-vue.
```typescript
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
test: {
setupFiles: ['vitest-browser-vue'], // Enables auto-cleanup
browser: {
enabled: true,
provider: 'playwright', // or 'webdriverio', 'preview'
},
},
})
```
--------------------------------
### Type-Safe Rerender Example
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/module-structure.md
Demonstrates type inference for component props and the RenderResult type, ensuring type-safe rerendering of components.
```typescript
// Props type is inferred from component
const screen = await render(Counter, {
props: { count: 0 } // TypeScript knows count is a number
})
// RenderResult<{ count: number }> type is inferred
await screen.rerender({ count: 5 }) // Type-safe
```
--------------------------------
### Vitest Browser Vue Configuration
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/README.md
Configures Vitest to use vitest-browser-vue, including setup files and browser-specific settings. Ensure 'vitest-browser-vue' is included in 'compilerOptions.types' or imported manually for TypeScript to recognize types.
```typescript
//vitest.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
// if the types are not picked up, add `vitest-browser-vue` to
// "compilerOptions.types" in your tsconfig or
// import `vitest-browser-vue` manually so TypeScript can pick it up
setupFiles: ['vitest-browser-vue'],
browser: {
// ... your config
},
},
})
```
--------------------------------
### Main Import Path
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/README.md
Imports the recommended main entry point for vitest-browser-vue, including auto-cleanup.
```typescript
// Main entry (recommended)
import { render, cleanup, config } from 'vitest-browser-vue'
```
--------------------------------
### Mount Component, Query DOM, and Interact with Component Methods
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/README.md
Demonstrates mounting a component, querying DOM elements by role, text, and placeholder, rerendering with new props, capturing emitted events, and unmounting the component.
```typescript
// Mount component
const screen = await render(Component, options)
// Query DOM
screen.getByRole('button')
screen.getByText('Click me')
screen.getByPlaceholder('Name')
// Component methods
await screen.rerender({ prop: 'value' })
const events = screen.emitted('eventName')
await screen.unmount()
// Debug
screen.debug()
```
--------------------------------
### Global Configuration Options
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/INDEX.md
Details the properties available under `config.global` for setting up global mocks, stubs, components, plugins, and directives.
```typescript
config.global.mocks // Mock global properties
config.global.stubs // Stub components
config.global.components // Register global components
config.global.plugins // Install Vue plugins
config.global.directives // Register directives
```
--------------------------------
### Import Vitest Browser Vue Config
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/api-reference/config.md
Import the global configuration object from vitest-browser-vue or vitest-browser-vue/pure.
```typescript
import { config } from 'vitest-browser-vue'
// or
import { config } from 'vitest-browser-vue/pure'
```
--------------------------------
### Global Configuration
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/INDEX.md
The `config` object allows for global configuration of mocks, stubs, plugins, and directives.
```APIDOC
## Configuration
### `config.global`
- `config.global.mocks`: Mock global properties.
- `config.global.stubs`: Stub components.
- `config.global.components`: Register global components.
- `config.global.plugins`: Install Vue plugins.
- `config.global.directives`: Register directives.
```
--------------------------------
### Main Entry: vitest-browser-vue
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/module-structure.md
The main entry point for vitest-browser-vue provides functions for rendering and cleaning up Vue components, along with global test configuration. It also includes side effects like automatic cleanup before each test and extending the Playwright page object.
```APIDOC
## Main Entry: vitest-browser-vue
### Description
Mounts a Vue component and returns locators and component methods, or unmounts all rendered components. It also re-exports the global test configuration object.
### Functions
- **render** (`(Component, options?) => RenderResult & PromiseLike>`): Mount a Vue component and return locators and component methods.
- **cleanup** (`() => void`): Unmount all rendered components.
### Re-exports
- **config** (`@vue/test-utils`): Global test configuration object.
### Type Exports
- **RenderResult** (`Props`): Return type of render() with component methods and locators.
- **ComponentRenderOptions** (`C, P`): Options parameter for render().
### Side Effects
- Registers `cleanup` via `beforeEach` hook.
- Extends the `page` object with a `render` method.
- Declares TypeScript module augmentation for `BrowserPage`.
```
--------------------------------
### ComponentRenderOptions
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/types.md
Options passed to the `render()` function to configure how a component is mounted.
```APIDOC
## ComponentRenderOptions
### Description
Options to configure component mounting during rendering.
### Properties
- `container` (`HTMLElement`): Custom DOM element where the component will be mounted. If omitted, a new `` is created and appended to `baseElement`. Defaults to auto-created.
- `baseElement` (`HTMLElement`): Root element for locator queries. Also used as the parent where `container` is appended if `container` is auto-created. Defaults to `document.body`.
### Inherited Properties (from ComponentMountingOptions)
All `@vue/test-utils` mount options are supported, including:
- `props` (`Partial
`): Props to pass to the component.
- `slots` (`Record`): Named or default slots.
- `global` (`GlobalMountOptions`): Global configuration (mocks, stubs, plugins, components, directives).
Note: `attachTo` is not supported and will raise an error. Use `container` instead.
### Type Parameters
- `C`: The Vue component type.
- `P`: The props type of the component.
```
--------------------------------
### Vitest Configuration for Automatic Cleanup
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/api-reference/cleanup.md
Shows how to configure Vitest to automatically call cleanup() before each test by adding 'vitest-browser-vue' to the setupFiles array in vitest.config.ts.
```typescript
// vitest.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
setupFiles: ['vitest-browser-vue'],
browser: {
// your browser config
}
}
})
```
--------------------------------
### Internal Architecture: src/index.ts Initialization
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/module-structure.md
Shows the initialization logic within src/index.ts, including extending the page object, registering the beforeEach hook, and declaring module augmentations.
```typescript
page.extend({
render,
[Symbol.for('vitest:component-cleanup')]: cleanup,
})
beforeEach(() => {
cleanup()
})
declare module 'vitest/browser' {
interface BrowserPage {
render: typeof render
}
}
```
--------------------------------
### Main Entry Imports
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/module-structure.md
Imports core functions and types from the main entry point of vitest-browser-vue.
```typescript
import { render, cleanup, config } from 'vitest-browser-vue'
import type { RenderResult, ComponentRenderOptions } from 'vitest-browser-vue'
```
--------------------------------
### Import Pure Entry
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/README.md
Import functions from the pure entry point of vitest-browser-vue for manual control over cleanup and without automatic page extension.
```typescript
import { render, cleanup, config } from 'vitest-browser-vue/pure'
```
--------------------------------
### Migration from @testing-library/vue
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/module-structure.md
Illustrates the change in import statements when migrating from @testing-library/vue to vitest-browser-vue. Highlights API similarities and differences.
```typescript
// Before: @testing-library/vue
import { render } from '@testing-library/vue'
// After: vitest-browser-vue (browser mode required)
import { render } from 'vitest-browser-vue'
```
--------------------------------
### render()
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/types.md
Renders a Vue component in a browser environment. It accepts the component and an optional options object for customization.
```APIDOC
## render()
### Description
Renders a Vue component in a browser environment. It accepts the component and an optional options object for customization.
### Method
`render(Component, options?)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **Component** (Component) - Required - The Vue component to render.
- **options** (ComponentRenderOptions) - Optional - An object containing options for rendering, such as props, slots, container, baseElement, global configuration, etc.
### Request Example
```typescript
import { render } from 'vitest-browser-vue'
import MyComponent from './MyComponent.vue'
// Minimal options
const screen = await render(MyComponent)
// With props
const screenWithProps = await render(MyComponent, {
props: { id: '123', disabled: false }
})
// With slots
const screenWithSlots = await render(MyComponent, {
slots: {
default: 'Default slot content
',
header: { template: 'Header
' }
}
})
// With custom container
const customDiv = document.createElement('div')
const screenWithCustomContainer = await render(MyComponent, {
container: customDiv,
baseElement: document.body.appendChild(customDiv)
})
// With global configuration
const screenWithGlobalConfig = await render(MyComponent, {
global: {
mocks: { $t: (k) => k },
stubs: { SomeComponent: true },
plugins: [i18n, router]
}
})
```
### Response
#### Success Response (RenderResult)
- Returns a `RenderResult` object which provides access to the rendered component and its associated utilities.
#### Response Example
```json
{
"//": "RenderResult object details are not fully specified in the source, but it typically includes methods to interact with the rendered component."
}
```
```
--------------------------------
### Global Mocking with Libraries
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/configuration.md
Mock global properties like $t or $locale, or integrate library instances such as Vue I18n by passing them to the global plugins configuration.
```typescript
import { config } from 'vitest-browser-vue'
import { createI18n } from 'vue-i18n'
// Simple mock
config.global.mocks = {
$t: (key) => key,
$locale: 'en',
}
// Using a library instance
const i18n = createI18n({
locale: 'en',
messages: {
en: { hello: 'Hello' },
fr: { hello: 'Bonjour' },
},
})
config.global.plugins = [i18n]
```
--------------------------------
### Core Vitest Browser Vue Functions
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/INDEX.md
Provides quick reference for the primary functions: `render` for mounting components, `cleanup` for unmounting, and `config` for global configuration.
```typescript
// Mount a component
const screen = await render(Component, options?: ComponentRenderOptions)
// Unmount all components
cleanup()
// Configure globally
config.global.mocks = { ... }
config.global.stubs = { ... }
config.global.plugins = [ ... ]
```
--------------------------------
### Direct @vue/test-utils vs. vitest-browser-vue render
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/module-structure.md
Compares the low-level @vue/test-utils mount function with the higher-level render function from vitest-browser-vue. Use vitest-browser-vue for a real browser environment and semantic locators.
```typescript
// Low level: Direct @vue/test-utils
import { mount } from '@vue/test-utils'
const wrapper = mount(Component, { props: {...} })
// Higher level: vitest-browser-vue wrapper
import { render } from 'vitest-browser-vue'
const screen = await render(Component, { props: {...} })
```
--------------------------------
### Re-rendering with New Props
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/README.md
Demonstrates how to update a component's props after initial render and verify the changes.
```typescript
const screen = await render(Display, { props: { count: 0 } })
await screen.rerender({ count: 5 })
await expect.element(screen.getByText('Count is 5')).toBeVisible()
```
--------------------------------
### Playwright Trace Viewing
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/README.md
Commands to enable trace recording and view recorded traces in Playwright.
```bash
pnpm test --browser.trace=on
pnpm playwright show-trace path/to/trace.zip
```
--------------------------------
### Per-Test Configuration with Mocks and Stubs
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/configuration.md
Configure mocks and stubs on a per-test basis using the render function's global options. This allows for isolated test configurations.
```typescript
import { config, render } from 'vitest-browser-vue'
import { beforeEach } from 'vitest'
beforeEach(() => {
// Reset between tests
config.global.mocks = {}
})
test('test with custom i18n', async () => {
const screen = await render(MyComponent, {
global: {
mocks: {
$t: (key) => `[${key}]`,
},
},
})
})
test('test with stubbed components', async () => {
const screen = await render(MyComponent, {
global: {
stubs: {
HeavyChart: { template: 'Chart Stub
' },
},
},
})
})
```
--------------------------------
### cleanup
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/README.md
Unmounts all components that were previously mounted using the `render()` function. This is crucial for ensuring tests are isolated and do not interfere with each other.
```APIDOC
## cleanup
### Description
Unmounts all components mounted via `render()`. This function ensures that the test environment is clean after a test runs, preventing state leakage between tests.
### Method
`cleanup()`
### Parameters
None
### Request Example
```typescript
cleanup()
```
### Response
No explicit return value.
### See
[cleanup() documentation](./api-reference/cleanup.md)
```
--------------------------------
### Run Tests with Inspector Enabled
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/advanced-patterns.md
Enable the browser test inspector by setting the PWDEBUG environment variable to 1. This allows for interactive debugging during test execution.
```bash
PWDEBUG=1 pnpm test --browser
```
--------------------------------
### config
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/README.md
Provides access to the global configuration object, which is re-exported from `@vue/test-utils`. This allows for setting global mocks, stubs, and plugins for all rendered components.
```APIDOC
## config
### Description
Global configuration object re-exported from `@vue/test-utils`. Use this to configure global settings like mocks, stubs, and plugins that apply to all component renders.
### Method
`config` (object)
### Parameters
None
### Request Example
```typescript
config.global.mocks = { $t: (k) => k }
config.global.stubs = { HeavyComponent: true }
config.global.plugins = [router, store]
```
### Response
An object representing the global configuration.
### See
[config documentation](./api-reference/config.md)
```
--------------------------------
### Global Mocking Configuration
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/README.md
Configures global mocks for common utilities like i18n and Vue Router.
```typescript
import { config } from 'vitest-browser-vue'
config.global.mocks = {
$t: (key) => key, // i18n
$route: { params: { id: '123' } }, // Vue Router
}
```
--------------------------------
### Test List Rendering and Item Count
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/advanced-patterns.md
Verify that lists of items are rendered correctly and that the total count of rendered items matches expectations.
```typescript
test('renders list of items', async () => {
const items = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' },
]
const screen = await render(ItemList, {
props: { items }
})
// All items rendered
await expect.element(screen.getByText('Apple')).toBeVisible()
await expect.element(screen.getByText('Banana')).toBeVisible()
await expect.element(screen.getByText('Orange')).toBeVisible()
// Correct count
const listItems = screen.getAllByRole('listitem')
expect(listItems).toHaveLength(3)
})
```
--------------------------------
### Global Configuration for Render Options
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/configuration.md
Set default configurations for all render calls using the config object. This includes global mocks, stubs, components, plugins, and directives.
```typescript
import { config } from 'vitest-browser-vue'
config.global.mocks = {
$t: (key) => key,
}
config.global.stubs = {
TransitionGroup: false,
}
config.global.components = {
MyGlobalComponent: () => import('./MyGlobalComponent.vue'),
}
config.global.plugins = [i18n, router]
config.global.directives = {
myDirective: (el, binding) => {
el.style.color = binding.value
}
}
```
--------------------------------
### Core Functions: render and cleanup
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/INDEX.md
The `render` function mounts a Vue component for testing, returning a `RenderResult` object. The `cleanup` function unmounts all mounted components.
```APIDOC
## Functions
### `render(Component, options?: ComponentRenderOptions)`
Mount a component for testing.
- **Component**: The Vue component to render.
- **options**: Optional `ComponentRenderOptions` for configuration.
**Returns**: A `RenderResult` object for interacting with the rendered component.
### `cleanup()`
Unmount all components that have been mounted by `render`.
```
--------------------------------
### Package.json Exports Field
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/module-structure.md
Defines the entry points for the vitest-browser-vue package, specifying default and type definitions for the main and pure modules.
```json
{
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./pure": {
"types": "./dist/pure.d.ts",
"default": "./dist/pure.js"
}
}
}
```
--------------------------------
### Using CSS Selectors vs. Accessible Queries
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/advanced-patterns.md
Prefer accessible query methods (e.g., `getByRole`, `getByLabelText`) over brittle CSS selectors. Accessible queries ensure tests align with user interaction and assistive technologies.
```typescript
// ✗ CSS selectors
screen.locator('div.my-class button')
// ✓ Accessible queries
screen.getByRole('button', { name: 'Click me' })
```
--------------------------------
### render
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/README.md
Mounts a Vue component into the document and returns an object with DOM references, query methods, and component control. It's the primary function for rendering components in tests.
```APIDOC
## render
### Description
Mounts a Vue component into the document. This function is the core of rendering components for testing purposes.
### Method
`render(Component, options?)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **Component** (VueComponent) - Required - The Vue component to render.
- **options** (ComponentRenderOptions) - Optional - Configuration options for rendering, including props, slots, and base elements.
### Request Example
```typescript
const screen = await render(MyComponent, { props: { count: 0 } })
```
### Response
#### Success Response
- **RenderResult** - An object containing methods and properties to interact with the rendered component and its DOM.
### Response Example
```typescript
{
container: HTMLElement,
baseElement: HTMLElement,
locator: Locator,
debug: (el?, maxLength?, options?) => void,
unmount: () => Promise,
emitted: (eventName?: string) => T[] | Record | undefined,
rerender: (props: Partial) => Promise
}
```
### See
[render() documentation](./api-reference/render.md)
```
--------------------------------
### View Collected Trace
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/advanced-patterns.md
View the collected trace file using the `playwright show-trace` command, providing the path to the generated trace zip file. Traces provide insights into component rendering, updates, and browser interactions.
```bash
pnpm playwright show-trace path/to/trace.zip
```
--------------------------------
### Enable Trace Collection
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/advanced-patterns.md
Enable trace collection for browser tests by setting the `--browser.trace` option to `on`. This captures detailed browser events and component lifecycle hooks for later analysis.
```bash
pnpm test --browser.trace=on
```
--------------------------------
### tsdown Build Configuration
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/module-structure.md
Configuration for the tsdown build tool, specifying entry points, output formats, and enabling TypeScript declaration files.
```typescript
export default defineConfig({
entry: ['./src/index.ts', './src/pure.ts'],
format: ['esm'],
dts: true,
})
```
--------------------------------
### Manual Cleanup Control
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/api-reference/page-methods.md
Shows how to manually control cleanup by importing render and cleanup directly from 'vitest-browser-vue/pure'. This is useful when automatic cleanup needs to be bypassed for specific test scenarios.
```typescript
import { render, cleanup } from 'vitest-browser-vue/pure'
test('manual cleanup', async () => {
const screen = await render(MyComponent)
// Do work...
cleanup() // Manually clean when you're ready
})
```
--------------------------------
### Render a Component with Vitest Browser Vue
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/INDEX.md
This snippet demonstrates how to render a Vue component using the `render` function from `vitest-browser-vue`. It shows basic usage with props and asserting element visibility.
```typescript
import { render } from 'vitest-browser-vue'
test('renders component', async () => {
const screen = await render(MyComponent, {
props: { count: 0 }
})
await expect.element(screen.getByText('Count is 0')).toBeVisible()
})
```
--------------------------------
### Render with Global Components
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/api-reference/render.md
Use this snippet to render a component with globally registered components. Ensure 'MyGlobalComponent' is defined in the global configuration.
```typescript
import { render } from 'vitest-browser-vue'
import { page } from 'vitest/browser'
test('with global components', async () => {
const screen = await render({
template: ''
}, {
global: {
components: {
MyGlobalComponent: {
template: 'Injected Component
'
}
}
}
})
await expect.element(screen.getByText('Injected Component')).toBeVisible()
})
```
--------------------------------
### Using Slots
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/README.md
Renders a component with content provided to its default and named slots.
```typescript
const screen = await render(Card, {
slots: {
default: 'Card content
',
header: 'Title
'
}
})
```
--------------------------------
### Render Component with Props
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/api-reference/page-methods.md
Renders a Vue component using the page.render() method, allowing for initial props to be passed. This is an alternative to directly importing and calling render().
```typescript
import { page } from 'vitest/browser'
import { test } from 'vitest'
import Counter from './Counter.vue'
test('counter increments', async () => {
const screen = await page.render(Counter, {
props: { initialCount: 1 }
})
await expect.element(screen.getByText('Count is 1')).toBeVisible()
})
```
--------------------------------
### cleanup()
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/api-reference/cleanup.md
Unmounts all rendered components and cleans up the testing environment. This function is typically called automatically before each test when vitest-browser-vue is imported directly.
```APIDOC
## cleanup()
### Description
Unmounts all rendered components and cleans up the testing environment.
### Method
`void`
### Parameters
None.
### Behavior
Iterates over all components mounted via `render()`, removes their parent nodes from the DOM if they are direct children of `document.body`, calls `unmount()` on the Vue Test Utils wrapper, and removes the wrapper from the internal tracking set. This ensures all rendered components are removed from the DOM, event listeners and subscriptions are torn down, and memory is released.
### Automatic Cleanup
When `vitest-browser-vue` is imported directly, `cleanup()` is automatically called before each test via a `beforeEach` hook, eliminating the need for manual calls in most cases.
### Manual Cleanup
Manual cleanup is required when importing from `vitest-browser-vue/pure`, testing specific cleanup scenarios, or when wanting to clean specific components (though `RenderResult.unmount()` is preferred for individual components).
### Examples
#### Automatic Cleanup (Default)
```typescript
import { render } from 'vitest-browser-vue'
import { test } from 'vitest'
import Counter from './Counter.vue'
test('first test', async () => {
const screen = await render(Counter)
// Test logic here
// cleanup() is called automatically after this test
})
test('second test', async () => {
// DOM is clean, no remnants from the first test
const screen = await render(Counter)
// Test logic here
})
```
#### Manual Cleanup with Pure Import
```typescript
import { render, cleanup } from 'vitest-browser-vue/pure'
import { test } from 'vitest'
import MyComponent from './MyComponent.vue'
test('manual cleanup example', async () => {
const screen = await render(MyComponent)
// Test logic here
cleanup() // Manually clean up all rendered components
})
```
#### Cleanup Specific Component
```typescript
import { render } from 'vitest-browser-vue'
import { test } from 'vitest'
import Component from './Component.vue'
test('cleanup specific component', async () => {
const screen1 = await render(Component, { props: { id: 1 } })
const screen2 = await render(Component, { props: { id: 2 } })
// Only unmount the first component
await screen1.unmount()
// screen2 is still mounted and can be tested
await screen2.getByText('Component 2').click()
// The second component is cleaned up by the beforeEach hook
})
```
#### Testing Cleanup Behavior
```typescript
import { render, cleanup } from 'vitest-browser-vue/pure'
import { test, expect } from 'vitest'
import App from './App.vue'
test('cleanup removes dom', async () => {
const screen = await render(App)
expect(document.body.innerHTML).not.toBe('')
cleanup()
// Component containers are removed
expect(screen.container.parentElement).toBeNull()
})
```
```
--------------------------------
### Render Vue Component
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/README.md
Mount a Vue component using the render function. This returns an object with DOM references and query methods.
```typescript
const screen = await render(Component, { props: { count: 0 } })
```
--------------------------------
### Component Lifecycle in Vitest Browser Vue
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/INDEX.md
Illustrates the typical lifecycle of a component test, from rendering to automatic cleanup.
```plaintext
render(Component)
↓
Mount via @vue/test-utils
↓
Assign test ID attributes
↓
Return RenderResult with locators and methods
↓
Before next test: cleanup() called automatically
↓
Unmount all components
```
--------------------------------
### Custom Container and Base Element for Rendering
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/configuration.md
Control the DOM structure for rendering components. Specify a custom container where the component's root element is mounted, and a base element for locator queries.
```typescript
// Default behavior: creates a div, appends to document.body
const screen1 = await render(MyComponent)
// Custom container
const customDiv = document.createElement('div')
const screen2 = await render(MyComponent, {
container: customDiv,
})
// Custom container and base element
const baseDiv = document.createElement('div')
document.body.appendChild(baseDiv)
const containerDiv = document.createElement('div')
baseDiv.appendChild(containerDiv)
const screen3 = await render(MyComponent, {
baseElement: baseDiv,
container: containerDiv,
})
```
--------------------------------
### Vitest Browser Configuration
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/configuration.md
Configure the browser environment where tests run using vitest.config.ts. Options include enabling the browser, setting headless mode, choosing a provider, and configuring Playwright-specific settings.
```typescript
// vitest.config.ts
import { defineConfig } from 'vitest/config'
import { playwright } from '@vitest/browser-playwright'
export default defineConfig({
test: {
browser: {
enabled: true,
headless: true, // Run without opening a browser window
provider: playwright(), // Use Playwright provider
instances: [
{ browser: 'chromium' },
{ browser: 'firefox' },
],
slowMo: 1000, // Slow down interactions (1000ms)
trace: true, // Enable Playwright traces
screenshotOnFailure: true, // Screenshot on test failure
},
},
})
```
--------------------------------
### Render Vue Component using page.render
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/README.md
Demonstrates rendering a Vue component using the `page.render` method, which is automatically injected by vitest-browser-vue. This snippet also shows the cleanup method.
```typescript
import { page } from 'vitest/browser'
test('counter button increments the count', async () => {
const screen = await page.render(Component, {
props: {
initialCount: 1,
}
})
screen.cleanup()
})
```
--------------------------------
### Rendering Component with Props
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/api-reference/render.md
Renders a Vue component and passes initial props to it. This is useful for testing component behavior with different data inputs. The props are passed via the `props` option in the `render` function.
```typescript
import { render } from 'vitest-browser-vue'
import Counter from './Counter.vue'
test('counter with initial value', async () => {
const screen = await render(Counter, {
props: {
initialCount: 5
}
})
await expect.element(screen.getByText('Count is 5')).toBeVisible()
})
```
--------------------------------
### Render in a Custom Container
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/api-reference/render.md
Render a component within a specified DOM element. The `container` and `baseElement` options control where the component is mounted.
```typescript
import { render } from 'vitest-browser-vue'
import App from './App.vue'
test('render in custom container', async () => {
const customRoot = document.createElement('div')
customRoot.id = 'app'
const screen = await render(App, {
container: customRoot,
baseElement: document.body.appendChild(customRoot)
})
// Component is mounted in customRoot
expect(screen.container.parentElement).toBe(customRoot)
})
```
--------------------------------
### Test Form Submission and Event Emission
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/advanced-patterns.md
Simulate user interactions like filling forms and clicking buttons to test submission logic and verify emitted events with their payloads.
```typescript
test('form submission', async () => {
const screen = await render(LoginForm)
// Fill inputs
await screen.getByLabel('Email').fill('test@example.com')
await screen.getByLabel('Password').fill('password123')
// Submit
await screen.getByRole('button', { name: 'Login' }).click()
// Verify events
const submitted = screen.emitted('submit')
expect(submitted).toHaveLength(1)
expect(submitted[0][0]).toEqual({
email: 'test@example.com',
password: 'password123',
})
})
```
```typescript
test('emits events with correct payload', async () => {
const screen = await render(ItemSelect)
// Emit event by interacting
await screen.getByRole('button', { name: 'Apple' }).click()
// Check emitted data
const selected = screen.emitted('select')
expect(selected).toHaveLength(1)
expect(selected[0][0]).toEqual({ id: 1, name: 'Apple' })
// Emit another
await screen.getByRole('button', { name: 'Orange' }).click()
expect(selected).toHaveLength(2)
})
```
--------------------------------
### Cleanup Specific Component
Source: https://github.com/vitest-community/vitest-browser-vue/blob/main/_autodocs/api-reference/cleanup.md
Illustrates how to unmount a specific component using its RenderResult.unmount() method, leaving other components mounted for further testing.
```typescript
import { render } from 'vitest-browser-vue'
import { test } from 'vitest'
import Component from './Component.vue'
test('cleanup specific component', async () => {
const screen1 = await render(Component, { props: { id: 1 } })
const screen2 = await render(Component, { props: { id: 2 } })
// Only unmount the first component
await screen1.unmount()
// screen2 is still mounted and can be tested
await screen2.getByText('Component 2').click()
// The second component is cleaned up by the beforeEach hook
})
```