Writing Tests
Relevant source files
The following files were used as context for generating this wiki page:
- packages/playwright/types/test.d.ts
- tests/playwright-test/reporter-html.spec.ts
- tests/playwright-test/only-changed.spec.ts
- tests/playwright-test/reporter-junit.spec.ts
- tests/playwright-test/reporter-blob.spec.ts
- tests/playwright-test/reporter-list.spec.ts
- tests/playwright-test/ui-mode-test-source.spec.ts
- CONTRIBUTING.md
Playwright Test is a framework for web testing and automation, designed to enable robust, cross-browser end-to-end testing. It provides a single API to test on Chromium, Firefox, and WebKit. The test runner is built for modern web applications, featuring auto-waits, web-first assertions, and powerful tooling to eliminate flaky tests.
This document outlines the core concepts and features for writing tests using Playwright Test, based on its internal type definitions and test suite. It covers test structure, execution control, advanced features like annotations and reporting, and how to leverage the framework's capabilities for creating reliable and maintainable tests.
Core Concepts
The foundation of writing tests in Playwright revolves around the test object, which is used to declare tests, groups, and hooks. Each test is executed in a fully isolated environment, ensuring that state from one test does not leak into another.
The test Object
The test object is the main entry point for creating tests. It provides methods for defining test cases, grouping them into suites, and controlling their execution.
The basic structure of a test is:
import { test, expect } from '@playwright/test';
test('basic test', async ({ page }) => {
// Test code using the 'page' fixture
});
Sources: packages/playwright/types/test.d.ts:1612-1618
The test function can be modified with various methods to alter its behavior:
| Method | Description |
|---|---|
test() | Declares a standard test case. |
test.only() | Declares a focused test. Only focused tests and suites will be run. |
test.skip() | Declares a skipped test. It can also be called conditionally within a test body. |
test.fixme() | Marks a test as "fixme", indicating it's broken and needs to be fixed. The test is not run. |
test.fail() | Marks a test as "should fail". Playwright runs the test and expects it to fail. |
test.slow() | Marks a test as "slow", tripling its default timeout. |
test.step() | Declares a logical step within a test, which is reflected in the test report. |
test.describe() | Declares a group of tests, or a suite. |
Sources: packages/playwright/types/test.d.ts:1610-2300
Test Suites with test.describe()
Tests can be organized into suites using test.describe(). This is useful for grouping related tests and applying common settings or hooks. Like individual tests, suites can also be focused (.only()) or skipped (.skip()).
test.describe('Error Pages', () => {
test('@regression passes', async ({}) => {
// ...
});
test('@smoke fails', async ({}) => {
// ...
});
});
Sources: tests/playwright-test/reporter-html.spec.ts:1820-1833
Test Information with TestInfo
Every test function, hook, and fixture can receive a TestInfo object. This object provides runtime information about the currently executing test, such as its title, status, retry count, and paths for output files and snapshots.
Key properties of TestInfo:
| Property | Type | Description |
|---|---|---|
title | string | The title of the currently running test. |
status | TestStatus | The actual status of the test (e.g., 'passed', 'failed'). Available after the test finishes. |
expectedStatus | TestStatus | The expected status of the test (e.g., 'passed' or 'failed' for test.fail). |
retry | number | The current retry number. 0 for the first run. |
annotations | Array | A list of annotations applied to the test. |
tags | Array<string> | A list of tags applied to the test. |
attach() | function | A function to attach files or buffers to the test report. |
outputPath() | function | Returns a path within the test's output directory. |
snapshotPath() | function | Returns the path to a snapshot file. |
Sources: packages/playwright/types/test.d.ts:1218-1546
Test Structure and Execution
Playwright provides hooks and steps to structure test logic and control execution flow.
Hooks
Hooks are functions that run before or after tests. They can be defined at the file level or within a test.describe block.
The following diagram illustrates the standard execution flow of tests and hooks.
This diagram shows the execution order of hooks around tests within a single worker process.
Sources: packages/playwright/types/test.d.ts:2018-2165
test.beforeEach()/test.afterEach(): Run before/after each test in the scope. Useful for setting up and tearing down per-test state.test.beforeAll()/test.afterAll(): Run once per worker process before/after all tests in the scope. Useful for expensive, shared setup.
Hooks can be given titles, which will appear in the test report, making the report more readable.
test.beforeEach('titled hook', () => {
console.log('titled hook');
});
test.beforeEach(() => {
console.log('anonymous hook');
});
Sources: tests/playwright-test/reporter-html.spec.ts:2713-2719
Test Steps
test.step() allows you to create logical divisions within a test. These steps are shown in the test report, providing a clear, hierarchical view of the test's execution. This is especially useful for breaking down complex actions into smaller, named parts.
test('example', async ({}) => {
await test.step('step title', async () => {
expect(1).toBe(1);
});
});
Sources: tests/playwright-test/reporter-html.spec.ts:1026-1032
Steps can be nested, and failed steps are clearly marked in the report, helping to quickly identify the point of failure.
Annotations and Tags
Tests and suites can be decorated with annotations and tags to add metadata.
- Tags: Used for filtering and grouping. Tags are strings starting with
@and can be specified in the test title or in the test details object. - Annotations: Key-value pairs that provide more structured metadata, such as linking to an issue tracker.
test('failing test with annotation', {
annotation: [
{ type: 'bug', description: 'Known issue' },
{ type: 'performance', description: 'slow test' }
],
tag: '@slow',
}, async ({ page }) => {
expect(1).toBe(2);
});
Sources: tests/playwright-test/reporter-markdown.spec.ts:110-119
This metadata is available in reports. For example, the HTML reporter displays tags as labels, and the JUnit reporter can embed annotations as custom properties.
Advanced Features
Running a Subset of Tests
Playwright provides several mechanisms to run a subset of your test suite, which is crucial for efficient development and CI pipelines.
Only Changed Files
The --only-changed CLI flag allows you to run only the tests that are affected by uncommitted or recent code changes. Playwright analyzes the dependency graph of your project to determine which test files to run.
The process flow for --only-changed is as follows:
This diagram illustrates how the --only-changed flag uses Git to determine which tests to execute.
Sources: tests/playwright-test/only-changed.spec.ts
This feature works with both end-to-end tests and component tests, understanding dependencies like helper files or components.
// If question.ts is changed, both a.spec.ts and b.spec.ts will run.
// a.spec.ts
import { answer, question } from './utils';
test('fails', () => { expect(question).toBe(answer); });
// b.spec.ts
import { answer, question } from './utils';
test('fails', () => { expect(question).toBe(answer); });
// utils.ts
export * from './answer';
export * from './question';
Sources: tests/playwright-test/only-changed.spec.ts:110-134
Reporting
Playwright Test includes a variety of built-in reporters to present test results.
| Reporter | Description | Configuration Example |
|---|---|---|
html | Generates a self-contained HTML report with detailed test results, traces, and attachments. | ['html', { outputFolder: 'playwright-report' }] |
list | Prints a real-time list of tests as they are being executed. Default in TTY environments. | ['list'] |
dot | Prints a single character for each test, providing a compact view. | ['dot'] |
junit | Generates a JUnit XML report, commonly used for CI integration. | ['junit', { outputFile: 'results.xml' }] |
json | Outputs a JSON file with detailed results. | ['json', { outputFile: 'report.json' }] |
blob | Creates a zip file containing all test results. Used for sharded test runs that need to be merged later. | ['blob', { outputDir: 'blob-report' }] |
Sources: packages/playwright/types/test.d.ts:22-33
Blob Reporter and Merging
The blob reporter is designed for distributed test execution. Each shard produces a .zip file containing its results. These files can then be aggregated into a single, comprehensive report using the playwright merge-reports command.
This process is essential for generating a unified HTML or JUnit report from a sharded CI run.
This diagram shows how blob reports from multiple shards are merged to create a final, consolidated report.
Sources: tests/playwright-test/reporter-blob.spec.ts
Test Artifacts
Playwright can automatically capture various artifacts during a test run, such as screenshots, videos, and traces. These are configured in playwright.config.ts under the use property.
screenshot: Captures screenshots. Modes includeon,off, andonly-on-failure.video: Records videos of test execution. Modes includeon,off, andretain-on-failure.trace: Records a detailed trace of the test execution, which can be viewed with the Playwright Trace Viewer. Modes includeon,off,retain-on-failure, andon-first-retry.
These artifacts are invaluable for debugging failed tests, as they provide a complete context of the application state at the time of failure.
Sources: tests/playwright-test/playwright.artifacts.spec.ts, packages/playwright/types/test.d.ts:2583-2640
Summary
Writing tests in Playwright is centered around the test object, which provides a rich API for defining, grouping, and controlling tests. By leveraging features like hooks, steps, annotations, and a powerful fixture model, developers can create structured and maintainable test suites. Advanced capabilities such as --only-changed, detailed reporting with artifacts, and support for sharded execution make Playwright a highly efficient and scalable framework for modern web application testing. A test is required for almost any new or modified functionality to ensure the framework remains reliable.
Sources: CONTRIBUTING.md:46-47