Test Generator (Codegen)
Relevant source files
The following files were used as context for generating this wiki page:
The Test Generator, commonly known as Codegen, is a utility within Playwright that enables users to record their interactions with a web page and automatically generate corresponding test scripts. Its primary purpose is to accelerate the test creation process by providing a functional script that can be saved and modified. Codegen can be initiated via the command line and supports generating code in various languages, including JavaScript/TypeScript (with Playwright Test), Python, Java, and .NET.
Codegen operates by launching a browser and a separate Inspector window. As the user interacts with the browser, such as clicking elements or typing text, the actions are captured and translated into Playwright API calls. These generated code snippets are displayed in real-time in the Inspector window, allowing the user to copy them or save them to a file.
Architecture
The Codegen feature is built on a client-server model. The main application logic resides in the RecorderApp class, which acts as a backend service. This service manages the browser instance, listens for user interaction events, and coordinates with the language generators to produce the script. The user-facing part is the Recorder UI, a React-based application that displays the generated code and provides controls for the recording session.
This diagram illustrates the high-level architecture of the Codegen system.
Invocation and Configuration
Codegen is typically launched from the command line. The basic command opens a browser and the Inspector window, ready to record actions.
npx playwright codegen <url>
Several command-line flags can be used to customize its behavior. These options are validated and tested in the project's test suites.
Sources: tests/installation/playwright-cli.spec.ts:20-53, tests/library/inspector/cli-codegen-1.spec.ts
CLI Options
| Option | Description | Example | Source |
|---|---|---|---|
--output <file> | Saves the generated code to a specified file. | npx playwright codegen --output=test.spec.js | [tests/installation/playwright-cli.spec.ts:21-28](https://github.com/microsoft/playwright/blob/HEAD/tests/installation/playwright-cli.spec.ts#L21-L28) |
--target <language> | Specifies the output language for the generated script. Supported targets include javascript, playwright-test, python, java, csharp. | npx playwright codegen --target=python | [tests/installation/playwright-cli.spec.ts:55-78](https://github.com/microsoft/playwright/blob/HEAD/tests/installation/playwright-cli.spec.ts#L55-L78) |
--user-data-dir <dir> | Starts the browser with a specific user data directory, preserving session data like cookies and local storage. | npx playwright codegen --user-data-dir=./my-user-data | [tests/installation/playwright-cli.spec.ts:30-48](https://github.com/microsoft/playwright/blob/HEAD/tests/installation/playwright-cli.spec.ts#L30-L48) |
Code Generation Logic
When a user performs an action in the browser, the RecorderApp backend receives a signal. This signal contains details about the action, such as the type of action (e.g., click, fill) and the target element. The backend then passes this information to a language-specific generator, which is responsible for converting the action into a line of code.
For instance, the JavaScriptLanguageGenerator class is responsible for generating JavaScript and TypeScript code. It contains methods to format different types of actions into valid Playwright Test syntax.
The process of generating a line of code from a user action can be visualized as follows:
Example: JavaScript Generation
The JavaScriptLanguageGenerator class implements the logic for creating Playwright Test scripts. It constructs the script by generating a header (imports, test definition), a series of action lines, and a footer.
// packages/playwright-core/src/server/codegen/javascript.ts:114-118
generateAction(action: Action): string {
// ...
switch (action.name) {
case 'click': {
// ... logic to generate click statement
}
// ... other cases
}
}
This structure allows for modular and extensible code generation, where adding support for a new action or language involves implementing the corresponding generation logic.
Sources: packages/playwright-core/src/server/codegen/javascript.ts:114-118
Selector Generation
A crucial part of Codegen is generating reliable and human-readable selectors for the elements the user interacts with. Playwright employs a sophisticated strategy to determine the best selector, prioritizing user-facing attributes.
The selector generation logic is extensively tested to ensure it produces optimal selectors in various scenarios, including handling elements in Shadow DOM and iframes.
Sources: tests/library/selector-generator.spec.ts
Selector Priority
The generator follows a specific order of preference when creating a selector. This hierarchy ensures that the most robust and readable selectors are chosen first.
This diagram shows the prioritized cascade for selector generation.
| Priority | Selector Type | Example | Rationale | Source |
|---|---|---|---|---|
| 1 | data-testid | getByTestId('submit-button') | Most resilient to code and text changes. Explicitly for testing. | [tests/library/selector-generator.spec.ts:98-101](https://github.com/microsoft/playwright/blob/HEAD/tests/library/selector-generator.spec.ts#L98-L101) |
| 2 | ARIA Role & Name | getByRole('button', { name: 'Sign In' }) | User-facing and accessible. Good for semantic HTML. | [tests/library/selector-generator.spec.ts:21-24](https://github.com/microsoft/playwright/blob/HEAD/tests/library/selector-generator.spec.ts#L21-L24) |
| 3 | Label Text | getByLabel('Password') | Connects form controls with their visible labels. | [tests/library/selector-generator.spec.ts:251-263](https://github.com/microsoft/playwright/blob/HEAD/tests/library/selector-generator.spec.ts#L251-L263) |
| 4 | Placeholder | getByPlaceholder('Search here...') | User-visible text for inputs. | [tests/library/selector-generator.spec.ts:185-188](https://github.com/microsoft/playwright/blob/HEAD/tests/library/selector-generator.spec.ts#L185-L188) |
| 5 | Text Content | getByText('Welcome back!') | Based on the visible text of an element. | [tests/library/selector-generator.spec.ts:38-41](https://github.com/microsoft/playwright/blob/HEAD/tests/library/selector-generator.spec.ts#L38-L41) |
| 6 | ID | '#submit-button' | Unique identifier, but can be dynamic in some apps. | [tests/library/selector-generator.spec.ts:121-127](https://github.com/microsoft/playwright/blob/HEAD/tests/library/selector-generator.spec.ts#L121-L127) |
| 7 | CSS Path / Ordinal | div >> nth=1 | Fallback for when no other robust selector can be found. | [tests/library/selector-generator.spec.ts:86-89](https://github.com/microsoft/playwright/blob/HEAD/tests/library/selector-generator.spec.ts#L86-L89) |
Recorder UI
The Recorder UI is a React application that provides the user with a real-time view of the generated test script. It includes a code editor, a list of recorded actions, and controls to manage the recording session.
The main component is defined in recorder.tsx. It uses CodeMirrorWrapper to display the generated code with syntax highlighting.
The UI communicates with the RecorderApp backend to receive updates. When the user performs an action, the backend processes it, generates the code, and sends an "action" event to the UI, which then updates the displayed script.
This sequence diagram illustrates the flow of information during a recording session.
Conclusion
The Test Generator (Codegen) is a powerful feature in Playwright designed to lower the barrier to entry for test automation. By recording user interactions and translating them into clean, readable test scripts, it helps developers and QAs quickly create a baseline for their tests. Its intelligent selector generation strategy and support for multiple languages make it a versatile tool for bootstrapping robust and maintainable automated tests.