Component Testing
Relevant source files
The following files were used as context for generating this wiki page:
- packages/playwright-ct-core/src/vitePlugin.ts
- tests/playwright-test/playwright.ct-build.spec.ts
- tests/playwright-test/playwright.ct-react.spec.ts
- packages/playwright/types/test.d.ts
- tests/playwright-test/test-server.spec.ts
- tests/playwright-test/ui-mode-test-ct.spec.ts
- tests/playwright-test/only-changed.spec.ts
- packages/web/src/components/codeMirrorWrapper.spec.tsx
Playwright's Component Testing feature allows developers to test individual UI components from frameworks like React and Vue in isolation. It uses a real browser environment, driven by the Playwright test runner, to mount, interact with, and assert the behavior of components. This approach combines the benefits of isolated component testing with the power and realism of end-to-end browser testing tools.
The core of this feature is a Vite-based development server that bundles the components and test code. A custom Vite plugin is used to manage the build process, including component discovery, dependency tracking, and caching, to provide a fast and efficient testing experience. This system is also integrated with Playwright's UI Mode, offering a rich, interactive environment for developing and debugging component tests.
Architecture Overview
The component testing architecture consists of three main parts: the Playwright Test Runner, a Vite-based Dev Server, and a custom Vite Plugin. The test runner discovers and executes tests, while the dev server is responsible for building and serving the components under test. The Vite plugin orchestrates the build process, extracts component metadata, and manages dependencies.
This diagram illustrates the high-level interaction between these components.
Build and Caching Process
The component testing build process is managed by a custom Vite plugin that optimizes for speed by implementing a sophisticated caching strategy. The process involves several key steps:
- Component Discovery: The plugin scans the test files to find all imported components. It extracts information such as the component's name, import source, and the test file that imports it.
- Cache Validation: It checks for a
metainfo.jsonfile in theplaywright/.cachedirectory. This file contains metadata about the last build, including Playwright version, Vite version, component list, and source file timestamps. If the cache is valid and no sources or components have changed, the existing build is used, skipping the transformation step. - Bundle Compilation: If the cache is invalid or sources have changed, Vite is invoked to build a new test bundle. During this process, the plugin collects dependency information for each component.
- Dependency Mapping: The plugin traces the dependency graph for each component source file. This information is stored in the
metainfo.jsoncache and is used by features like--only-changedto determine which tests to run when a source file is modified. - Cache Update: The
metainfo.jsonfile is updated with the new component list, source timestamps, and dependency information.
This flow ensures that the test bundle is only rebuilt when necessary, significantly speeding up test execution.
This diagram shows the decision-making process for building or reusing the component test bundle.
Sources: packages/playwright-ct-core/src/vitePlugin.ts:114-206, tests/playwright-test/playwright.ct-build.spec.ts:241-294
metainfo.json Structure
The build process generates a metainfo.json file that is crucial for caching and dependency tracking.
| Key | Type | Description |
|---|---|---|
version | string | The version of Playwright Core used for the build. |
viteVersion | string | The version of Vite used for the build. |
registerSourceHash | string | A SHA1 hash of the injected registration script. |
components | ImportInfo[] | An array of objects, each describing a component imported in a test. |
sources | object | A map of source file paths to their last modification timestamp. |
deps | object | A map of component source file paths to an array of their dependency file paths. |
Sources: packages/playwright-ct-core/src/vitePlugin.ts:91-101, tests/playwright-test/playwright.ct-build.spec.ts:24-32
Configuration
Component testing is configured within the playwright.config.ts file. A dedicated defineConfig function is available for each supported framework (e.g., @playwright/experimental-ct-react).
Key Configuration Options
| Option | Type | Description |
|---|---|---|
use.ctPort | number | Specifies the port for the component testing dev server. |
use.ctViteConfig | object | Allows passing a custom Vite configuration object to be merged with Playwright's default Vite config. This can be used to add plugins, like basicSsl for HTTPS testing. |
use.baseURL | string | Sets the base URL for the test page, which can be useful for testing components that make relative network requests. |
use.ignoreHTTPSErrors | boolean | When using a dev server with HTTPS, this option is needed to ignore self-signed certificate errors. |
Sources: packages/playwright/types/test.d.ts, tests/playwright-test/playwright.ct-build.spec.ts:430-445, tests/playwright-test/playwright.ct-react.spec.ts:410-413
Example Configuration
// playwright.config.ts
import { defineConfig } from '@playwright/experimental-ct-react';
import basicSsl from '@vitejs/plugin-basic-ssl';
export default defineConfig({
testDir: './src',
use: {
// Port for the dev server
ctPort: 3100,
// Enable HTTPS for the dev server
ignoreHTTPSErrors: true,
ctViteConfig: {
plugins: [basicSsl()],
preview: {
https: true
}
}
},
});
Sources: tests/playwright-test/playwright.ct-build.spec.ts:430-445
Writing Component Tests
Component tests are written in standard test files (e.g., .spec.tsx) and use the test and expect objects from the corresponding Playwright component testing package.
The mount function
The primary tool for component testing is the mount function, which is provided as a fixture. It takes a JSX element as an argument, renders it in the browser, and returns a Locator pointing to the root element of the mounted component.
// src/button.test.tsx
import { test, expect } from '@playwright/experimental-ct-react';
import { Button } from './button';
test('should render a button', async ({ mount }) => {
// Mount the component and get a locator to its root
const component = await mount(<Button>Click Me</Button>);
// Use the locator to make assertions
await expect(component).toHaveText('Click Me');
});
Sources: tests/playwright-test/playwright.ct-react.spec.ts:15-26
Test Execution Flow
The following diagram shows the sequence of events during a typical component test run.
This diagram illustrates the interaction between the test runner, the mount fixture, the Vite server, and the browser during a component test.
Sources: tests/playwright-test/playwright.ct-react.spec.ts:15-26, packages/playwright-ct-core/src/vitePlugin.ts
UI Mode and Test Server
Component tests are fully integrated with Playwright's UI Mode and Test Server, providing an interactive and efficient development experience.
UI Mode
When running component tests with the --ui flag, developers get a live view of their tests and components. Key features include:
- Live Reloading: The UI automatically updates and re-runs tests when either a test file or a component source file is changed.
- File Watching: The system watches the entire dependency graph, so changes in imported utility files or child components also trigger a re-run.
- Interactive DOM Inspector: The mounted component can be inspected directly in the browser.
- Source Viewing: The source code of the test and its components are displayed alongside the test results.
Sources: tests/playwright-test/ui-mode-test-ct.spec.ts
Test Server
The test-server command provides a WebSocket-based API to interact with the test runner. This is used internally by UI Mode but can also be used by other tools. For component testing, the test server exposes capabilities like:
startDevServer: Programmatically starts the Vite dev server.findRelatedTestFiles: Given a list of source files (e.g., component files), it returns the list of test files that depend on them. This is powered by the dependency graph stored inmetainfo.json.clearCache: Removes theplaywright/.cachedirectory.
Sources: tests/playwright-test/test-server.spec.ts:128-142
Dependency Analysis for --only-changed
Playwright's component testing supports the --only-changed flag, which intelligently runs only the tests affected by local file changes. This is achieved through a dependency analysis performed during the build process.
The custom Vite plugin builds a dependency graph that maps every test file to the source files it imports, including transitive dependencies. When --only-changed is used, Playwright compares the changed files (as reported by git) against this dependency graph to determine the minimal set of tests to execute.
For example, if contents.ts is changed, any test that directly or indirectly imports a component that uses contents.ts will be scheduled to run.
Sources: tests/playwright-test/only-changed.spec.ts:192-243, packages/playwright-ct-core/src/vitePlugin.ts:219-232