### setup() Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Convenience function that creates test hooks and runs the appropriate test runner setup. It automatically selects the setup function based on the detected test runner (Vitest, Jest, Cucumber, Bun) and skips setup if already running within a Vitest environment. ```APIDOC ## `setup()` ### Description Convenience function that creates test hooks and runs the appropriate test runner setup. ### Signature ```typescript export async function setup(options?: Partial): Promise ``` ### Parameters #### options - **options** (`Partial`) - Optional - Test configuration options. Defaults to `{}`. ### Details - Automatically selects setup function based on detected test runner - Skips setup if running within a Vitest environment that already resolved test utils - Supported runners: Vitest, Jest, Cucumber, Bun ### Example ```typescript import { setup } from '@nuxt/test-utils' beforeAll(async () => { await setup({ rootDir: import.meta.dirname, }) }) ``` ``` -------------------------------- ### Start Nuxt Test Server with Environment Variables Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Starts the Nuxt test server with custom environment variables. Ensure '@nuxt/test-utils' is installed. ```typescript import { startServer } from '@nuxt/test-utils' await startServer({ env: { DEBUG: 'nuxt:*' } }) ``` -------------------------------- ### GitHub Actions CI/CD Workflow Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/GUIDE.md Example steps for a GitHub Actions workflow to install dependencies, run unit tests, and run E2E tests. ```yaml - name: Install dependencies run: npm ci - name: Run tests run: npm run test - name: Run E2E tests run: npm run test:e2e ``` -------------------------------- ### Nuxt Module Installation Wizard Hook Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/module.md The onInstall hook for the Nuxt module, which runs an interactive setup wizard for initial configuration. ```typescript async onInstall(nuxt) { await runInstallWizard(nuxt) } ``` -------------------------------- ### Vitest Environment Setup Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/vitest-environment.md Provides a complete DOM environment with Vue and Nuxt integration for running unit and component tests. It exposes a setup function that returns a teardown function. ```APIDOC ## Environment Setup ### Signature ```typescript export default Environment { name: 'nuxt' viteEnvironment: 'client' async setup(global, environmentOptions): { teardown(): void } } ``` ### Configuration Register the Nuxt environment in vitest.config.ts: ```typescript import { defineVitestConfig } from '@nuxt/test-utils/config' export default defineVitestConfig({ test: { environment: 'nuxt', environmentOptions: { nuxt: { rootDir: './app', domEnvironment: 'happy-dom', url: 'http://localhost:3000', } } } }) ``` Or for specific test files: ```typescript // my.nuxt.test.ts // @vitest-environment nuxt ``` ``` -------------------------------- ### Install Dependencies and Playwright Browsers Source: https://github.com/nuxt/test-utils/blob/main/CONTRIBUTING.md Installs project dependencies using pnpm and downloads the Chromium browser for Playwright testing. ```bash pnpm install && pnpm playwright install chromium ``` -------------------------------- ### Activate Development System Source: https://github.com/nuxt/test-utils/blob/main/CONTRIBUTING.md Prepares the development environment by running the necessary build and setup commands. ```bash pnpm dev:prepare ``` -------------------------------- ### StartServerOptions Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/types.md Options available when starting the test server for Nuxt applications. ```APIDOC ## StartServerOptions ### Description Options for starting the test server. ### Interface Definition ```typescript interface StartServerOptions { env?: Record } ``` ``` -------------------------------- ### Setup Nuxt Test Environment Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Use this function to set up the test environment for E2E tests. It automatically selects the appropriate test runner setup and skips setup if already running within a compatible Vitest environment. It's typically called within `beforeAll`. ```typescript import { setup } from '@nuxt/test-utils' beforeAll(async () => { await setup({ rootDir: import.meta.dirname, }) }) ``` -------------------------------- ### Run Tests and Prepare for Release Source: https://github.com/nuxt/test-utils/blob/main/CONTRIBUTING.md Executes prepack, example tests, and prepares the development environment for testing changes. ```bash pnpm prepack pnpm test:examples pnpm dev:prepare ``` -------------------------------- ### Setup DevTools Integration in Nuxt Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/module.md This code snippet sets up the DevTools integration for Vitest within Nuxt. It should only run when Nuxt is in development mode. The `setupDevTools` function is called after the DevTools are initialized, and the Vitest wrapper can be started if configured to do so. ```typescript if (!nuxt.options.dev) return onDevToolsInitialized(async () => { await setupDevTools(vitestWrapper, nuxt) }, nuxt) if (options.startOnBoot) { vitestWrapper.start() } ``` -------------------------------- ### StartServerOptions Interface Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/types.md Interface for options when starting the test server, allowing environment variable configuration. ```typescript interface StartServerOptions { env?: Record } ``` -------------------------------- ### H3 v1 Event Handler Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/vitest-environment.md Example of an H3 v1 event handler registration. Ensure `h3` is installed for this version. ```typescript // h3 v1 event handler import type { EventHandler, H3Event } from 'h3' registerEndpoint('/api/test', ((event: H3Event) => { return { test: 'data' } }) as EventHandler) ``` -------------------------------- ### Install Nuxt Kit Dependency Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/errors.md Ensure `@nuxt/kit` is installed in your project dependencies. This is required for `@nuxt/test-utils` to function correctly, especially when loading Nuxt configuration. ```bash npm install nuxt # or @nuxt/bridge for Nuxt 2 ``` -------------------------------- ### Example Usage of NuxtPage goto Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/types.md Demonstrates navigating to a new route using the NuxtPage goto method with custom waitUntil options. ```typescript const page = await createPage('/') as NuxtPage await page.goto('/about', { waitUntil: 'hydration' }) ``` -------------------------------- ### Catch Test Setup Errors with createTest Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/errors.md Use a try-catch block around `createTest` and `hooks.beforeAll` to handle potential errors during test setup. This is particularly useful for catching missing dependencies like `playwright-core`. ```typescript import { createTest } from '@nuxt/test-utils' describe('my tests', () => { let hooks beforeAll(async () => { try { hooks = createTest({ rootDir: import.meta.dirname, browser: true, }) await hooks.beforeAll() } catch (error) { if (error.message.includes('playwright-core')) { // Handle missing browser dependency console.log('Install playwright-core for browser tests') } else { throw error } } }) afterAll(async () => { if (hooks) { await hooks.afterAll() } }) }) ``` -------------------------------- ### startServer Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Starts the Nuxt test server. It can be configured with environment variables and waits for the server to be ready before resolving. It handles both development and production server modes. ```APIDOC ## `startServer()` Starts the Nuxt test server. ### Signature ```typescript export async function startServer(options?: StartServerOptions): Promise ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | `StartServerOptions` | No | `{}` | Server options including environment variables | | options.env | `Record` | No | `{}` | Environment variables to pass to server process | ### Details - Assigns a random port if not specified - Runs `nuxi _dev` in dev mode or `node server/index.mjs` in production - Sets up environment with `PORT`, `HOST`, `NODE_ENV` - Waits for server readiness with timeout (`serverStartTimeout`) - Dev server waits for successful response and absence of `__NUXT_LOADING__` marker ### Throws - **Error** - If server process exits before becoming ready - **Error** - If timeout exceeded waiting for server readiness ### Example ```typescript import { startServer } from '@nuxt/test-utils' await startServer({ env: { DEBUG: 'nuxt:*' } }) ``` ``` -------------------------------- ### Configure Happy DOM Environment Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/vitest-environment.md Use Happy DOM for a faster, lightweight DOM implementation. Install with `npm install --save-dev happy-dom`. ```typescript export default defineVitestConfig({ test: { environmentOptions: { nuxt: { domEnvironment: 'happy-dom' } } } }) ``` -------------------------------- ### Nuxt Module Setup Hook Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/module.md The main setup hook for the Nuxt module, executed in test or development mode. It configures import mocking, adds Vite plugins, and initializes Vitest. ```typescript async setup(options, nuxt) { // Configures import mocking await setupImportMocking(nuxt) // Adds Vite plugins addVitePlugin(NuxtRootStubPlugin({ ... })) // Sets up DevTools integration (dev mode only) // Configures TypeScript compilation // Initializes Vitest wrapper } ``` -------------------------------- ### Example Usage Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/playwright.md Demonstrates how to use the Playwright test fixture for navigating to pages and interacting with the application. ```APIDOC ## Example ```typescript import { test, expect } from '@nuxt/test-utils/playwright' import { fileURLToPath } from 'node:url' test.use({ nuxt: { rootDir: fileURLToPath(new URL('./app', import.meta.url)) } }) test('navigates to about page', async ({ goto }) => { // Uses baseURL from Nuxt server and waits for hydration const response = await goto('/about', { waitUntil: 'hydration' }) expect(response?.ok()).toBe(true) }) test('can use page methods', async ({ page }) => { await page.goto('/') const heading = await page.locator('h1') await expect(heading).toContainText('Welcome') }) ``` ``` -------------------------------- ### Source File Mapping Example Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/README.md Illustrates the mapping between source files and their corresponding API reference documentation within the Nuxt Test Utils project. ```text src/ ├── config.ts → api-reference/config.md ├── e2e.ts → api-reference/e2e.md │ ├── browser.ts │ ├── context.ts │ ├── nuxt.ts │ ├── server.ts │ ├── setup/ │ ├── run.ts │ └── types.ts ├── playwright.ts → api-reference/playwright.md ├── runtime-utils/ → api-reference/runtime-utils.md │ ├── mount.ts │ ├── render.ts │ ├── mock.ts │ └── utils/suspended.ts ├── environments/vitest/ → api-reference/vitest-environment.md ├── module.ts → api-reference/module.md └── utils.ts ``` -------------------------------- ### Nuxt Configuration Example Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/configuration.md Define runtime configuration for your Nuxt application. Environment variables with the NUXT_ prefix are mapped to runtimeConfig. ```typescript export default defineNuxtConfig({ runtimeConfig: { apiUrl: 'http://localhost:3000', public: { apiUrl: 'http://localhost:3000' } } }) ``` -------------------------------- ### startVitest() Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Runs Vitest tests programmatically. It supports options for root directory, development mode, watch mode, test runner, and global setup. ```APIDOC ## `startVitest()` Runs Vitest tests programmatically. ### Signature ```typescript export async function runTests(opts: RunTestOptions): Promise ``` ### Parameters #### Path Parameters * **opts.rootDir** (`string`) - Required - Test root directory * **opts.dev** (`boolean`) - Optional - Run in dev mode (Default: `false`) * **opts.watch** (`boolean`) - Optional - Run in watch mode (Default: `false`) * **opts.runner** (`'vitest'`) - Optional - Test runner (only vitest supported) (Default: `'vitest'`) * **opts.globalSetup** (`boolean`) - Optional - Include global setup (Default: `true`) ### Details - Sets `NUXT_TEST_DEV` environment variable if dev mode - Launches Vitest via `startVitest()` from vitest/node - Enables vitest globals and configures inline dependencies - Exits with code 1 if tests fail ``` -------------------------------- ### Install Playwright Core Dependency Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/errors.md Install the `playwright-core` dependency to resolve 'Playwright Core Not Found' errors. This is required when using browser features without the necessary dependency. ```bash npm install --save-dev playwright-core ``` -------------------------------- ### createTest() Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Creates test hooks for managing the test lifecycle (setup, teardown, before/after each). It automatically detects the test runner and handles fixture loading, server start, browser creation, and cleanup. ```APIDOC ## `createTest()` ### Description Creates test hooks for managing the test lifecycle (setup, teardown, before/after each). ### Signature ```typescript export function createTest(options: Partial): TestHooks ``` ### Parameters #### Path Parameters - **options** (`Partial`) - Required - Test configuration options ### Return Type Returns a `TestHooks` object with lifecycle functions: ```typescript interface TestHooks { beforeEach: () => void afterEach: () => void afterAll: () => Promise beforeAll: () => Promise setup: () => Promise // deprecated, use beforeAll ctx: TestContext } ``` ### Details - Automatically detects test runner (Vitest, Jest, Cucumber, Bun) from environment - `beforeAll()` runs fixture loading, building, server start, and browser creation - `afterAll()` cleans up server process, closes Nuxt instance, closes browser, and runs teardown functions - `beforeEach()` and `afterEach()` manage test context lifecycle ### Example ```typescript import { createTest } from '@nuxt/test-utils' const { beforeAll, afterAll, beforeEach, afterEach } = createTest({ rootDir: '/path/to/nuxt/app', browser: true, }) describe('my tests', () => { beforeAll(async () => { await beforeAll() }) afterAll(async () => { await afterAll() }) beforeEach(() => { beforeEach() }) afterEach(() => { afterEach() }) it('works', () => { // test code }) }) ``` ``` -------------------------------- ### Create Playwright Browser Instance Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Launches a Playwright browser instance for end-to-end testing. Requires 'playwright-core' to be installed. ```typescript import { createBrowser } from '@nuxt/test-utils' await createBrowser() ``` -------------------------------- ### Configure JSDOM Environment Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/vitest-environment.md Use JSDOM for a more complete, albeit heavier, DOM implementation. Install with `npm install --save-dev jsdom`. ```typescript export default defineVitestConfig({ test: { environmentOptions: { nuxt: { domEnvironment: 'jsdom' } } } }) ``` -------------------------------- ### Setup Import Mocking Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/module.md Automatically configures the import mocking system in test or development mode. Enables the use of `mockNuxtImport()` and `mockComponent()` macros. ```typescript if (nuxt.options.test || nuxt.options.dev) { await setupImportMocking(nuxt) } ``` -------------------------------- ### defineVitestConfig Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/config.md Creates an async Vite configuration function with automatic Nuxt environment setup. It simplifies the process of configuring Vitest for Nuxt projects by providing sensible defaults and handling environment setup. ```APIDOC ## `defineVitestConfig()` Creates an async Vite configuration function with automatic Nuxt environment setup. ### Signature ```typescript export function defineVitestConfig( config?: ViteUserConfig & { test?: VitestConfig } ): UserConfigFnPromise ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | config | `ViteUserConfig & { test?: VitestConfig }` | No | `{}` | Base Vite/Vitest configuration | ### Return Type Returns an async function (compatible with `defineConfig` export) that resolves to a merged configuration object. ### Details - When no specific environment is set, automatically creates a workspace with two projects: one using Nuxt environment and one using the default environment - The Nuxt project matches files: `**/*.nuxt.{test,spec}.*` and `{test,tests}/nuxt/**` - Incompatible with `projects` or `workspace` options in the test config - All options are overrideable via the `environmentOptions.nuxt` object ### Example ```typescript import { defineVitestConfig } from '@nuxt/test-utils/config' export default defineVitestConfig({ test: { globals: true, } }) ``` ``` -------------------------------- ### Start Test Server with Environment Variables Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/configuration.md Configure the test server environment by setting specific environment variables. This is useful for debugging and controlling server behavior during tests. ```typescript await startServer({ env: { DEBUG: 'nuxt:*', LOG_LEVEL: 'debug', NODE_ENV: 'test', } }) ``` -------------------------------- ### Vitest Configuration with Nuxt Environment Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/vitest-environment.md Provides a full example of Vitest configuration for a Nuxt project, specifying the 'nuxt' environment and common options like globals, include/exclude paths, environment-specific options, and coverage settings. ```typescript import { defineVitestConfig } from '@nuxt/test-utils/config' export default defineVitestConfig({ test: { environment: 'nuxt', globals: true, include: ['tests/**/*.test.ts'], exclude: ['node_modules', 'dist'], environmentOptions: { nuxt: { rootDir: './app', domEnvironment: 'happy-dom', url: 'http://localhost:3000', rootId: 'app', overrides: { future: { compatibilityVersion: 4 } }, mock: { intersectionObserver: true, indexedDb: false, } } }, coverage: { provider: 'v8', reporter: ['text', 'html'], } } }) ``` -------------------------------- ### Playwright Test Example with Nuxt Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/playwright.md Example of using the Playwright test fixture with Nuxt. Demonstrates navigation to a page and waiting for hydration, as well as using standard Playwright page methods. ```typescript import { test, expect } from '@nuxt/test-utils/playwright' import { fileURLToPath } from 'node:url' test.use({ nuxt: { rootDir: fileURLToPath(new URL('./app', import.meta.url)) } }) test('navigates to about page', async ({ goto }) => { // Uses baseURL from Nuxt server and waits for hydration const response = await goto('/about', { waitUntil: 'hydration' }) expect(response?.ok()).toBe(true) }) test('can use page methods', async ({ page }) => { await page.goto('/') const heading = await page.locator('h1') await expect(heading).toContainText('Welcome') }) ``` -------------------------------- ### Playwright Basic Setup with Nuxt Root Directory Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/configuration.md Configure Playwright to use a specific Nuxt root directory for testing. ```typescript // playwright.config.ts import { defineConfig } from '@playwright/test' export default defineConfig({ use: { nuxt: { rootDir: fileURLToPath(new URL('./app', import.meta.url)) } } }) ``` -------------------------------- ### Timing Options for Tests Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/configuration.md Configure timeouts for test setup, teardown, and server startup. Platform-specific values are provided for Windows and other operating systems. ```typescript { setupTimeout: 120000, // or 240000 on Windows teardownTimeout: 30000, // or 60000 on Windows serverStartTimeout: 60000, // or 120000 on Windows waitFor: 0, } ``` -------------------------------- ### mountSuspended() Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/runtime-utils.md Mounts a Vue component within a Nuxt environment with async setup support. It automatically cleans up previous test components and wraps the component in a helper that suspends until all async setup completes, providing access to Nuxt injections and auto-imports. ```APIDOC ## mountSuspended() ### Description Mounts a Vue component within a Nuxt environment with async setup support. ### Signature ```typescript export async function mountSuspended( component: T, options?: WrapperOptions ): Promise> ``` ### Parameters #### component - **component** (`T`) - Required - Vue component to mount #### options - **options** (`WrapperOptions`) - Optional - Mount options ### Mount Options Extends `@vue/test-utils` mount options with Nuxt-specific settings: ```typescript type WrapperOptions = ComponentMountingOptions & { route?: RouteLocationRaw | false // route to navigate to scoped?: boolean // run setup in effect scope } ``` - **route** (`RouteLocationRaw | false`) - Optional - Navigate to a route before component setup (false to skip navigation) - **scoped** (`boolean`) - Optional - Run component setup in an effect scope for cleanup (default: false) - All standard `@vue/test-utils` options supported: `props`, `slots`, `global`, `attachTo`, etc. ### Return Type Returns a proxy wrapper combining `@vue/test-utils` wrapper with the mounted component: ```typescript type WrapperResult = VueWrapper & { setupState: Record setProps: (props: object) => void } ``` The wrapper automatically: - Delegates component methods and properties to the mounted component - Provides access to `setupState` from component setup function - Includes all `@vue/test-utils` wrapper methods ### Details - Automatically cleans up previous test components via `cleanupAll()` - Wraps component in a helper that suspends until all async setup completes - Provides access to Nuxt injections and auto-imports - Supports route navigation during mount ### Example ```typescript import { mountSuspended } from '@nuxt/test-utils/runtime' import MyComponent from './MyComponent.vue' it('mounts with async setup', async () => { const wrapper = await mountSuspended(MyComponent, { props: { title: 'Test Title' }, route: '/about', }) expect(wrapper.text()).toContain('Test Title') expect(wrapper.setupState.someAsyncValue).toBeDefined() }) it('can mount with slots', async () => { const wrapper = await mountSuspended(MyComponent, { slots: { default: 'Slot content' } }) expect(wrapper.html()).toContain('Slot content') }) ``` ``` -------------------------------- ### Minimal playwright.config.ts Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/GUIDE.md This minimal configuration for Playwright automatically loads the Nuxt fixture, builds if necessary, starts the server, and launches the browser. ```typescript import { defineConfig } from '@playwright/test' import { test } from '@nuxt/test-utils/playwright' test.use({ nuxt: { rootDir: import.meta.dirname } }) export default defineConfig({}) ``` -------------------------------- ### NuxtVitestOptions Interface Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/module.md Defines the configuration options for the test utils module, including options for starting Vitest and logging. ```typescript interface NuxtVitestOptions { startOnBoot?: boolean logToConsole?: boolean vitestConfig?: VitestConfig } ``` -------------------------------- ### Construct Absolute URL for Test Server Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Constructs an absolute URL pointing to the test server. Provide a path to get the full URL. ```typescript export function url(path: string): string ``` -------------------------------- ### H3 v2 Event Handler Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/vitest-environment.md Example of an H3 v2 event handler registration. Requires `h3-next` for this version. ```typescript // h3 v2 event handler import type { EventHandler, H3Event } from 'h3-next' registerEndpoint('/api/test', ((event: H3Event) => { return { test: 'data' } }) as EventHandler) ``` -------------------------------- ### Initialize Vitest UI Wrapper Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/module.md Initializes a Vitest UI wrapper in development mode for interactive testing. It logs the UI URL when started and the exit code when exited. ```typescript const wrapper = createVitestWrapper(options, nuxt) wrapper.ons({ started({ uiUrl }) { logger.info(`Vitest UI starting on ${uiUrl}`) }, exited({ exitCode }) { logger.info(`Vitest exited with code ${exitCode}`) } }) ``` -------------------------------- ### Fetch Component HTML on Server Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/runtime-utils.md Use `$fetchComponent` to render a component on the server and get its HTML. This function requires the server to be running and makes a request to a special `/__nuxt_component_test__/` endpoint. It's ideal for server-side rendering tests. ```typescript export function $fetchComponent( filepath: string, props?: Record ): Promise ``` -------------------------------- ### RunTestOptions Interface Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/types.md Interface for options when running tests programmatically. Configure root directory, development mode, watch mode, test runner, and global setup inclusion. ```typescript interface RunTestOptions { rootDir: string dev?: boolean watch?: boolean runner?: 'vitest' globalSetup?: boolean } ``` -------------------------------- ### Recommended Test File Structure Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/GUIDE.md Illustrates the recommended directory structure for organizing Nuxt tests, including fixture, unit, Nuxt environment, and end-to-end tests. ```tree project/ ├── test/ │ ├── fixture/ # Nuxt app under test │ │ ├── nuxt.config.ts │ │ ├── app.vue │ │ ├── pages/ │ │ └── components/ │ │ │ ├── unit/ # Non-Nuxt tests │ │ ├── utils.test.ts │ │ └── helpers.test.ts │ │ │ ├── nuxt/ # Nuxt environment tests │ │ ├── components.nuxt.test.ts │ │ ├── composables.nuxt.test.ts │ │ └── api.nuxt.test.ts │ │ │ └── e2e/ # Playwright tests │ ├── navigation.spec.ts │ └── authentication.spec.ts │ vitest.config.ts playwright.config.ts nuxt.config.ts ``` -------------------------------- ### Mount Component with Async Setup Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/runtime-utils.md Use `mountSuspended` to mount a Vue component in a Nuxt environment, supporting async setup and route navigation. It automatically cleans up previous components and provides access to Nuxt injections. ```typescript import { mountSuspended } from '@nuxt/test-utils/runtime' import MyComponent from './MyComponent.vue' it('mounts with async setup', async () => { const wrapper = await mountSuspended(MyComponent, { props: { title: 'Test Title' }, route: '/about', }) expect(wrapper.text()).toContain('Test Title') expect(wrapper.setupState.someAsyncValue).toBeDefined() }) ``` ```typescript import { mountSuspended } from '@nuxt/test-utils/runtime' import MyComponent from './MyComponent.vue' it('can mount with slots', async () => { const wrapper = await mountSuspended(MyComponent, { slots: { default: 'Slot content' } }) expect(wrapper.html()).toContain('Slot content') }) ``` -------------------------------- ### Playwright ConfigOptions Type Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/types.md Defines Playwright device configuration for Nuxt, including setup options. ```typescript type ConfigOptions = { nuxt: Partial | undefined defaults: { nuxt: Partial | undefined } } ``` -------------------------------- ### fetch() Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Makes a fetch request to the test server. It takes a path and optional request options. ```APIDOC ## `fetch()` Makes a fetch request to the test server. ### Signature ```typescript export function fetch(path: string, options?: RequestInit): Promise ``` ### Parameters #### Path Parameters * **path** (`string`) - Required - The path for the fetch request. * **options** (`RequestInit`) - Optional - Request initialization options. ``` -------------------------------- ### WrapperSuspendedResult Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/types.md The return type from `mountSuspended()` and `renderSuspended()`, providing component setup state and potential re-rendering capabilities. ```APIDOC ## WrapperSuspendedResult ### Description Return type from `mountSuspended()` and `renderSuspended()`. ### Type Definition ```typescript type WrapperSuspendedResult = WrapperFnResult & { setupState: SetupState } ``` ### Additional Properties | Property | Type | Description | |----------|------|-------------| | setupState | Record | Component setup function return value | For `renderSuspended()`, also includes: - `rerender(props: object): Promise` - Update component props ``` -------------------------------- ### $fetchComponent Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/runtime-utils.md Renders a component on the server and returns the resulting HTML. This utility is useful for server-side rendering tests. ```APIDOC ## $fetchComponent ### Description Renders a component on the server and returns the HTML output. This function is designed for testing server-side rendering (SSR) behavior of Nuxt components. ### Method `$fetchComponent(filepath: string, props?: Record): Promise` ### Parameters #### Path Parameters - **filepath** (string) - Required - The file path to the component that needs to be rendered. - **props** (object) - Optional - An object containing the props to be passed to the component during rendering. ### Details - This function only works when a server is running. - It makes a request to a special internal endpoint `/__nuxt_component_test__/`. - Useful for verifying that your components render correctly on the server. ``` -------------------------------- ### Get Current Test Context Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Retrieves the current test context. Throws an error if no context is available. ```typescript export function useTestContext(): TestContext ``` -------------------------------- ### loadFixture() Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Loads a Nuxt fixture application from disk. It resolves the fixture root directory, creates a build directory if not in dev mode, loads the Nuxt instance with merged configuration, and sets up a teardown function. ```APIDOC ## `loadFixture()` ### Description Loads a Nuxt fixture application from disk. ### Signature ```typescript export async function loadFixture(): Promise ``` ### Details - Resolves the fixture root directory from `options.rootDir`, `testDir + fixture`, or current working directory - Creates build directory under `.nuxt/test/{randomId}` if not in dev mode - Loads Nuxt instance with merged configuration - Sets up teardown function to clean build directory ### Throws - **Error** - If no valid Nuxt app is found ``` -------------------------------- ### Define TestOptions Interface Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/types.md Configuration options for setting up tests. Includes directories, build settings, timeouts, and browser options. ```typescript interface TestOptions { testDir: string fixture: string configFile: string rootDir: string buildDir: string nuxtConfig: NuxtConfig build: boolean dev: boolean setupTimeout: number teardownTimeout: number serverStartTimeout: number waitFor: number browser: boolean runner: TestRunner logLevel: number browserOptions: { type: 'chromium' | 'firefox' | 'webkit' launch?: LaunchOptions } server: boolean host?: string port?: number env?: StartServerOptions['env'] } ``` -------------------------------- ### Get Browser Instance Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Retrieves the current Playwright browser instance. Creates a new one if it does not exist. ```typescript export async function getBrowser(): Promise ``` -------------------------------- ### Directory and Build Options for Tests Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/configuration.md Specify directories for tests, fixtures, Nuxt app root, and build output. Also configure the Nuxt config file name and whether to build the fixture before tests. ```typescript { testDir: 'test', // Default test directory fixture: 'fixture', // Default fixture name rootDir: '.', // Nuxt app root directory buildDir: '.nuxt/test', // Build output directory configFile: 'nuxt.config', // Nuxt config file name build: true, // Build fixture before tests dev: false, // Development mode } ``` -------------------------------- ### $fetch() Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Makes a typed fetch request using ofetch to the test server. It supports specifying the request method and body, and automatically handles JSON parsing and error handling. ```APIDOC ## `$fetch()` Makes a typed fetch request using ofetch to the test server. ### Details - Uses ofetch for JSON parsing and error handling - Compatible with Nitro API responses ### Example ```typescript const data = await $fetch('/api/users', { method: 'POST', body: { name: 'John' } }) ``` ``` -------------------------------- ### url() Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Constructs an absolute URL to the test server. It takes a path and returns the full URL string. ```APIDOC ## `url()` Constructs an absolute URL to the test server. ### Signature ```typescript export function url(path: string): string ``` ### Parameters #### Path Parameters * **path** (`string`) - Required - The path to construct the URL for. ``` -------------------------------- ### getBrowser() Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Gets the current browser instance, creating one if needed. This function returns a Playwright `Browser` instance. ```APIDOC ## getBrowser() ### Description Gets the current browser instance, creating one if needed. ### Signature ```typescript export async function getBrowser(): Promise ``` ### Return Type Returns a `playwright-core` `Browser` instance. ``` -------------------------------- ### LoadNuxtOptions Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/config.md Options for loading a Nuxt instance, allowing for partial overrides of dotenv and Nuxt configuration. ```APIDOC ## LoadNuxtOptions Options for loading a Nuxt instance: ```typescript interface LoadNuxtOptions { dotenv?: Partial overrides?: Partial } ``` ``` -------------------------------- ### Vitest Environment Signature Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/vitest-environment.md Defines the structure for the custom Vitest environment, including its name, Vite environment type, and setup function. ```typescript export default Environment { name: 'nuxt' viteEnvironment: 'client' async setup(global, environmentOptions): { teardown(): void } } ``` -------------------------------- ### Enable Corepack Source: https://github.com/nuxt/test-utils/blob/main/CONTRIBUTING.md Enables Corepack to manage package manager versions, specifically for using pnpm. ```bash corepack enable ``` -------------------------------- ### WrapperSuspendedResult Type Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/types.md The return type from `mountSuspended()` and `renderSuspended()`, including component setup state. For `renderSuspended()`, it also includes a `rerender` function. ```typescript type WrapperSuspendedResult = WrapperFnResult & { setupState: SetupState } ``` -------------------------------- ### Load Nuxt Fixture Application Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Loads a Nuxt fixture application from disk. This function resolves the fixture root directory, creates a build directory if not in dev mode, and loads the Nuxt instance with merged configurations. It will throw an error if no valid Nuxt app is found. ```typescript await loadFixture() ``` -------------------------------- ### ConfigOptions Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/types.md Playwright device configuration options for Nuxt testing environments. ```APIDOC ## ConfigOptions ### Description Playwright device configuration for Nuxt. ### Type Definition ```typescript type ConfigOptions = { nuxt: Partial | undefined defaults: { nuxt: Partial | undefined } } ``` ``` -------------------------------- ### Minimal vitest.config.ts Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/GUIDE.md Use this minimal configuration for Vitest. It automatically loads Nuxt configuration, sets up the Nuxt environment, configures inline dependencies, and applies environment options. ```typescript import { defineVitestConfig } from '@nuxt/test-utils/config' export default defineVitestConfig() ``` -------------------------------- ### Create a New Branch Source: https://github.com/nuxt/test-utils/blob/main/CONTRIBUTING.md Checks out a new Git branch to work on your changes, following a descriptive naming convention. ```bash git checkout -b my-new-branch ``` -------------------------------- ### Create Nuxt Page Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Creates a new browser page for testing. Automatically navigates to the specified path and enhances the `goto` method with custom `waitUntil` options like 'hydration' or 'route'. ```typescript const page = await createPage('/', { javaScriptEnabled: true }) await page.goto('/about', { waitUntil: 'hydration' }) ``` -------------------------------- ### `test` Fixture Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/playwright.md The `test` fixture extends Playwright's base test with Nuxt-specific options, providing automatic setup and teardown of a Nuxt application for each test. ```APIDOC ## `test` Fixture ### Description A Playwright test fixture that automatically sets up and tears down a Nuxt application for each test. ### Signature ```typescript export const test: TestType ``` ### Test Fixture Fixture The `test` fixture extends Playwright's base test with Nuxt-specific options: ```typescript type TestOptions = { goto: (url: string, options?: GotoOptions) => Promise } type WorkerOptions = { _nuxtHooks: TestHooks } type ConfigOptions = { nuxt: Partial | undefined defaults: { nuxt: Partial | undefined } } ``` ``` -------------------------------- ### Vitest URL and Base URL Configuration Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/vitest-environment.md Configures the URL and base URL for the Vitest environment. The `window.location` is set to this URL, and all relative URLs resolve against it. ```typescript // From environmentOptions const url = joinURL( environmentOptions.nuxt?.url ?? 'http://localhost:3000', environmentOptions.nuxtRuntimeConfig?.app?.baseURL || '/' ) // window.location is set to this URL // All relative URLs resolve against it ``` ```typescript export default defineVitestConfig({ test: { environmentOptions: { nuxt: { url: 'http://localhost:8080' } } } }) // In tests: expect(window.location.origin).toBe('http://localhost:8080') ``` -------------------------------- ### Server Configuration for Tests Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/configuration.md Control the test server, including enabling/disabling it, setting the host and port, and providing environment variables. ```typescript { server: true, // Start test server host: undefined, // External server URL port: undefined, // Server port env: {}, } ``` -------------------------------- ### Configuring Vitest with Nuxt Test Utils Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/vitest-environment.md Shows how to configure Vitest to enable global test fixtures and integrate with Nuxt Test Utils by adding types to `vitest.config.ts`. ```typescript /// import { defineVitestConfig } from '@nuxt/test-utils/config' export default defineVitestConfig({ test: { globals: true, } }) ``` -------------------------------- ### GetVitestConfigOptions Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/config.md Configuration object passed to `getVitestConfigFromNuxt()`. It requires the Nuxt instance and the Vite configuration. ```APIDOC ## GetVitestConfigOptions Configuration object passed to `getVitestConfigFromNuxt()`: ```typescript interface GetVitestConfigOptions { nuxt: Nuxt viteConfig: NuxtViteConfig } ``` ``` -------------------------------- ### Get Vitest Config from Nuxt Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/configuration.md Use `getVitestConfigFromNuxt` to retrieve Vitest configuration based on your Nuxt project, allowing for environment variable overrides and compatibility version settings. ```typescript import { getVitestConfigFromNuxt } from '@nuxt/test-utils/config' export default defineConfig( await getVitestConfigFromNuxt({ dotenv: { fileName: '.env.test.local' }, overrides: { future: { compatibilityVersion: 4 } } }) ) ``` -------------------------------- ### Mock Nuxt Component Definition Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/runtime-utils.md Use `mockComponent` to mock Nuxt component definitions. This can be done by providing component options, a factory function that returns the component, or a setup function. ```typescript import { mockComponent } from '@nuxt/test-utils/runtime' mockComponent('MyComponent', { props: { title: String }, template: '
{{ title }}
' }) // Or with factory function mockComponent('~/components/Complex.vue', async () => { const { default: ActualComponent } = await import('./RealComponent.vue') return { ...ActualComponent, setup(props, ctx) { // Custom setup logic return ActualComponent.setup?.(props, ctx) } } }) // Or with setup function mockComponent('Header', (props, { slots }) => { return () => (
{slots.default?.()}
) }) ``` -------------------------------- ### Nuxt Test Hooks for Lifecycle Management Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/GUIDE.md Provides lifecycle management for test setup and teardown operations. Use `createTest` to access `beforeAll`, `beforeEach`, `afterEach`, and `afterAll` hooks. ```typescript const { beforeAll, beforeEach, afterEach, afterAll } = createTest(options) // beforeAll() - Load fixture, build, start server, launch browser // beforeEach() - Set test context // afterEach() - Clear test context // afterAll() - Stop server, close browser, run teardowns ``` -------------------------------- ### buildFixture() Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Builds the loaded Nuxt fixture application by calling Nuxt's `buildNuxt()` function. It temporarily changes the logger level and only runs if the `build` option is true. ```APIDOC ## `buildFixture()` ### Description Builds the loaded Nuxt fixture application. ### Signature ```typescript export async function buildFixture(): Promise ``` ### Details - Calls Nuxt's `buildNuxt()` with the loaded instance - Temporarily changes logger level to `logLevel` option - Only runs if `options.build` is true ``` -------------------------------- ### Create Test Hooks for E2E Testing Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Use `createTest` to generate lifecycle hooks for your end-to-end tests. Configure options like `rootDir` and `browser` to manage test environment setup and teardown. ```typescript import { createTest } from '@nuxt/test-utils' const { beforeAll, afterAll, beforeEach, afterEach } = createTest({ rootDir: '/path/to/nuxt/app', browser: true, }) describe('my tests', () => { beforeAll(async () => { await beforeAll() }) afterAll(async () => { await afterAll() }) beforeEach(() => { beforeEach() }) afterEach(() => { afterEach() }) it('works', () => { // test code }) }) ``` -------------------------------- ### Generate Vitest Config from Nuxt Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/config.md Use this function to generate a complete Vitest configuration based on your loaded Nuxt instance. It merges Nuxt-specific environment options, resolved dependencies, plugins, and test environment setups. ```typescript import { getVitestConfigFromNuxt } from '@nuxt/test-utils/config' export default defineConfig( await getVitestConfigFromNuxt() ) ``` -------------------------------- ### Enhanced `goto()` Method Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/playwright.md The `goto()` method provided by the Nuxt Playwright fixture supports custom wait conditions beyond standard Playwright options. ```APIDOC ## Enhanced `goto()` Method The `goto()` method supports custom wait conditions: ```typescript interface GotoOptions extends Omit { waitUntil?: 'hydration' | 'route' | Playwright waitUntil options } ``` **waitUntil options:** - `'hydration'` - Waits for Nuxt to complete hydration (`useNuxtApp().isHydrating === false`) - `'route'` - Waits for the current route to match the navigated URL - Other values follow standard Playwright behavior ``` -------------------------------- ### Set Nuxt Build Timeout for Dev Server Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/errors.md Set a custom timeout for the Nuxt build process to help resolve 'Dev server is still starting up' errors. This is useful when the dev server responds with 503 or `__NUXT_LOADING__`. ```typescript await startServer({ env: { NUXT_BUILD_TIMEOUT: '60000' } }) ``` -------------------------------- ### createBrowser Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/api-reference/e2e.md Launches a Playwright browser instance for testing. It supports different browser types (chromium, firefox, webkit) and passes launch options to the Playwright launcher. The browser instance is stored in the test context. ```APIDOC ## `createBrowser()` Launches a Playwright browser instance. ### Signature ```typescript export async function createBrowser(): Promise ``` ### Details - Uses Playwright browser type from `options.browserOptions.type` (chromium, firefox, webkit) - Passes `launch` options to browser launcher - Stores browser instance in test context ### Throws - **Error** - If 'playwright-core' dependency is not installed - **Error** - If invalid browser type specified ``` -------------------------------- ### NuxtVitestOptions Type Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/types.md Module configuration options for Nuxt Vitest. These settings control aspects like automatic startup and logging behavior. ```APIDOC ## NuxtVitestOptions Type ### Description Module configuration options. ### Interface Definition ```typescript interface NuxtVitestOptions { startOnBoot?: boolean logToConsole?: boolean vitestConfig?: VitestConfig } ``` ### Properties | Property | Type | Default | Description | |----------|------|---------|-------------| | startOnBoot | boolean | `false` | Start Vitest UI on app boot | | logToConsole | boolean | `false` | Log Vitest output to console | | vitestConfig | object | undefined | Custom Vitest configuration | ``` -------------------------------- ### Component Unit Test with Nuxt Test Utils Source: https://github.com/nuxt/test-utils/blob/main/_autodocs/GUIDE.md Perform unit tests on Nuxt components within a simulated Nuxt environment. Ensure your component tests have the `.nuxt.spec.ts` or `.nuxt.test.ts` extension and can leverage Nuxt's auto-imports and plugins. Remember to await mounting for asynchronous setup. ```typescript // tests/components/MyComponent.nuxt.spec.ts import { mountSuspended } from '@nuxt/test-utils/runtime' import { describe, it, expect } from 'vitest' import MyComponent from '~/components/MyComponent.vue' describe('MyComponent', () => { it('renders', async () => { const wrapper = await mountSuspended(MyComponent, { props: { title: 'Test' } }) expect(wrapper.text()).toContain('Test') }) }) ```