Playwright 16 ๐ญ Codegen โ Recording tests with npx playwright codegen
Playwright Codegen is the built-in test generator that watches you interact with a web page and translates those actions into executable test code. Instead of manually inspecting the DOM and writing locators by hand, you launch npx playwright codegen, click through your application in the opened browser window, and watch the generated TypeScript appear line by line in the Playwright Inspector. The tool prioritizes role, text, and test-id based locators, producing code that is more resilient to UI changes than hand-written CSS selectors.
This chapter covers the complete Codegen workflow: launching the generator against a local or remote URL, recording actions and assertions, using the Locator Picker to extract individual selectors, and applying emulation options for viewports, devices, color schemes, and geolocation. It also addresses the limitations of recorded codeโmissing assertions, overly specific locators, and the absence of page object structureโand explains how to refine raw recordings into maintainable tests. By the end, you will understand when Codegen accelerates test authoring and when manual editing is essential.
Key point: Codegen produces a first draft, not a finished test. It captures what you did, not what you meant to verify. The generated code is a starting point that requires deliberate editingโsimplifying locators, adding meaningful assertions, and extracting reusable patternsโbefore it belongs in a test suite.
Why Codegen exists
The locator-writing bottleneck. Writing reliable Playwright tests requires choosing the right locator strategy: getByRole over CSS classes, getByText over XPath, and test IDs over structural selectors. For developers new to Playwright, or for unfamiliar applications where the DOM structure is not yet understood, determining the correct locator for every interaction is slow and error-prone. Codegen automates the first pass by observing the page and selecting locators according to Playwright’s priority hierarchy.
The discovery problem. When testing a third-party application or a legacy codebase with inconsistent markup, manually exploring the DOM to find stable selectors can consume more time than writing the test itself. Codegen opens a browser, lets you navigate naturally, and records the interactions as you perform them. The resulting code reveals which locators Playwright considers reliable for each element, serving as a live tutorial for the application’s accessible structure.
The assertion gap. Codegen records actionsโclicks, fills, navigationsโbut it does not know what outcome you expect. Unless you explicitly use the assertion toolbar buttons, the generated test will perform a sequence of interactions and then end, verifying nothing. This limitation is intentional: a recorder can capture behavior, but only the test author knows what constitutes success. Understanding this boundary is essential to using Codegen effectively rather than treating its output as production-ready.
a. Launching Codegen and recording actions
The codegen command opens two windows: a browser window where you interact with the target application, and the Playwright Inspector window where generated code appears in real time. The URL argument is optional; you can launch without it and navigate inside the browser window afterward.
// Terminal command: launch codegen against a local development server
// npx playwright codegen http://localhost:5173
// The command opens Chromium by default.
// To target a specific browser:
// npx playwright codegen --browser=firefox http://localhost:5173
// To save the recorded authentication state for reuse:
// npx playwright codegen --save-storage=auth.json http://localhost:5173
// To load a previously saved authentication state:
// npx playwright codegen --load-storage=auth.json http://localhost:5173
Once the browser opens, every meaningful interactionโclicking a button, filling an input, selecting an option, pressing Enterโis translated into a Playwright action. The Inspector displays the generated TypeScript as you work. Clicking the Record button pauses recording; clicking Clear resets the generated code so you can start over. When finished, the Copy button places the entire generated test on your clipboard.
The generator does not record every mouse movement. It listens for semantic browser events: click, fill, press, selectOption, and navigation events. Hovering over an element without clicking produces nothing. Scrolling produces nothing unless it triggers a lazy-load that changes the DOM. This selectivity keeps the output focused on intentional interactions rather than incidental mouse activity.
b. Recording assertions with the toolbar
Action recording alone produces tests that execute without verifying. Codegen provides three assertion tools in the Inspector toolbar: Assert visibility, Assert text, and Assert value. To use them, click the assertion button, then click the target element in the browser window. Codegen inserts the corresponding expect call at the current position in the recording.
// Recorded actions WITHOUT assertions (incomplete test)
await page.goto('https://demo.playwright.dev/todomvc');
await page.getByPlaceholder('What needs to be done?').click();
await page.getByPlaceholder('What needs to be done?').fill('Buy milk');
await page.getByPlaceholder('What needs to be done?').press('Enter');
// Recorded actions WITH assertions (complete test)
await page.goto('https://demo.playwright.dev/todomvc');
await page.getByPlaceholder('What needs to be done?').click();
await page.getByPlaceholder('What needs to be done?').fill('Buy milk');
await page.getByPlaceholder('What needs to be done?').press('Enter');
// Assert that the new todo item is visible with the correct text
await expect(page.getByText('Buy milk')).toBeVisible(); // โ
recorded via toolbar
The three assertion types map to the most common verification needs. Assert visibility produces expect(locator).toBeVisible(). Assert text produces expect(locator).toHaveText() or toContainText(). Assert value produces expect(locator).toHaveValue() for form inputs. These cover the majority of simple checks, but complex assertionsโcounting elements, checking URLs, verifying network responsesโmust be written manually after recording.
c. Generating locators with the Pick Locator tool
Sometimes you need a single locator rather than a complete test. The Pick Locator button (available after pausing recording) lets you hover over any element in the browser window and see the locator Playwright considers most appropriate. Clicking the element places that locator in the playground field next to the button, where you can edit it and see the matching elements highlighted in the browser.
// Example locators that Pick Locator might generate for different elements:
// A submit button with accessible role and name
page.getByRole('button', { name: 'Submit' })
// An email input identified by its label
page.getByLabel('Email address')
// A navigation link identified by its text content
page.getByRole('link', { name: 'Sign in' })
// A form field identified by placeholder (when no label exists)
page.getByPlaceholder('Search products')
// A custom component with a test ID
page.getByTestId('checkout-summary')
The Locator Picker prioritizes the same hierarchy as Codegen’s automatic recording: getByRole first, then getByText or getByLabel, then getByPlaceholder, and finally getByTestId. If multiple elements match a candidate locator, the tool refines itโtypically by adding a { name: '...' } filter or scoping to a parent elementโuntil the locator uniquely identifies the target. This is the single most valuable feature for developers learning Playwright’s locator philosophy: it demonstrates, element by element, which selectors the framework considers stable.
Complete Example Session
// ============================================
// PART 1: LAUNCHING CODEGEN
// ============================================
// Terminal:
// npx playwright codegen --viewport-size="1280,720" https://demo.playwright.dev/todomvc
// Two windows open: a Chromium browser at the TodoMVC demo,
// and the Playwright Inspector showing an empty test.
// ============================================
// PART 2: RECORDING INITIAL NAVIGATION
// ============================================
// The Inspector automatically generates the goto:
await page.goto('https://demo.playwright.dev/todomvc/#/');
// ============================================
// PART 3: RECORDING A FILL ACTION
// ============================================
// Click into the "What needs to be done?" input and type "Write tests"
await page.getByPlaceholder('What needs to be done?').click();
await page.getByPlaceholder('What needs to be done?').fill('Write tests');
// ============================================
// PART 4: RECORDING A KEYBOARD PRESS
// ============================================
// Press Enter to submit the todo
await page.getByPlaceholder('What needs to be done?').press('Enter');
// ============================================
// PART 5: RECORDING A SECOND TODO
// ============================================
await page.getByPlaceholder('What needs to be done?').fill('Run tests');
await page.getByPlaceholder('What needs to be done?').press('Enter');
// ============================================
// PART 6: ADDING AN ASSERTION VIA TOOLBAR
// ============================================
// Click "Assert text" in the toolbar, then click the first todo item
await expect(page.getByText('Write tests')).toBeVisible();
// ============================================
// PART 7: ADDING A SECOND ASSERTION
// ============================================
// Click "Assert text" again, click the second todo item
await expect(page.getByText('Run tests')).toBeVisible();
// ============================================
// PART 8: RECORDING A CHECKBOX TOGGLE
// ============================================
// Click the checkbox to mark the first todo as complete
await page.getByRole('checkbox', { name: 'Toggle Todo' }).first().check();
// ============================================
// PART 9: RECORDING NAVIGATION TO A FILTER
// ============================================
// Click the "Active" filter link
await page.getByRole('link', { name: 'Active' }).click();
// ============================================
// PART 10: FINAL RECORDED TEST
// ============================================
// The complete generated test, copied from the Inspector:
import { test, expect } from '@playwright/test';
test('test', async ({ page }) => {
await page.goto('https://demo.playwright.dev/todomvc/#/');
await page.getByPlaceholder('What needs to be done?').click();
await page.getByPlaceholder('What needs to be done?').fill('Write tests');
await page.getByPlaceholder('What needs to be done?').press('Enter');
await page.getByPlaceholder('What needs to be done?').fill('Run tests');
await page.getByPlaceholder('What needs to be done?').press('Enter');
await expect(page.getByText('Write tests')).toBeVisible();
await expect(page.getByText('Run tests')).toBeVisible();
await page.getByRole('checkbox', { name: 'Toggle Todo' }).first().check();
await page.getByRole('link', { name: 'Active' }).click();
});
The ten parts above trace a complete Codegen session: launching the tool, recording navigation and form interactions, adding assertions through the toolbar, and producing a runnable test. The generated test performs the recorded actions and verifies the two todo items are visible, but it does not assert the outcome of the checkbox toggle or the Active filter navigationโthose assertions must be added manually because the recorder cannot infer them.
Quick Reference
The Codegen Command Options
| Option | Purpose | Example |
|---|---|---|
--browser | Target browser | --browser=firefox |
--device | Emulate device | --device="iPhone 13" |
--viewport-size | Set viewport | --viewport-size="1280,720" |
--color-scheme | Emulate dark/light | --color-scheme=dark |
--save-storage | Save auth state | --save-storage=auth.json |
--load-storage | Load auth state | --load-storage=auth.json |
The Assertion Toolbar Buttons
| Button | Generated Code | Use Case |
|---|---|---|
| Assert visibility | expect(locator).toBeVisible() | Element appears after action |
| Assert text | expect(locator).toHaveText() | Content matches expectation |
| Assert value | expect(locator).toHaveValue() | Input contains expected value |
Locator Priority Hierarchy
| Priority | Method | Example |
|---|---|---|
| 1 | getByRole | page.getByRole('button', { name: 'Save' }) |
| 2 | getByLabel | page.getByLabel('Username') |
| 3 | getByPlaceholder | page.getByPlaceholder('Search') |
| 4 | getByText | page.getByText('Welcome back') |
| 5 | getByTestId | page.getByTestId('submit-btn') |
Best Practices
โ Do This:
// Launch codegen against a specific URL to skip manual navigation
// npx playwright codegen http://localhost:3000/login
// Use assertion toolbar buttons during recording
await expect(page.getByText('Success')).toBeVisible(); // โ
// Use --load-storage for authenticated pages to avoid re-login
// npx playwright codegen --load-storage=auth.json http://localhost:3000
// Use the Pick Locator tool to learn stable selectors for key elements
page.getByRole('button', { name: 'Checkout' }); // โ
// Record in a viewport that matches your test configuration
// npx playwright codegen --viewport-size="1440,900" http://localhost:3000
// Copy the recording, then simplify locators that are more specific than needed
page.getByRole('button', { name: 'Submit' }); // โ
simpler than a scoped version
โ Don’t Do This:
// Don't record without assertions and call it a test
await page.getByRole('button', { name: 'Submit' }).click(); // โ no verification
// Don't keep nth() chains that break when list order changes
await page.getByRole('checkbox').nth(2).check(); // โ fragile if items reorder
// Don't commit raw recordings with no test names or structure
test('test', async ({ page }) => { ... }); // โ meaningless test name
// Don't use CSS or XPath selectors when role-based ones exist
page.locator('.btn-primary'); // โ codegen would use getByRole
// Don't record against production data that changes between runs
await page.getByPlaceholder('Search').fill('John Doe'); // โ user may not exist
// Don't skip the locator repair step for nth() or structural selectors
await page.locator('div > ul > li:nth-child(2)'); // โ use Pick Locator instead
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Test does nothing after actions | No assertions recorded | Use toolbar buttons during recording |
| Locator breaks after UI reorder | Codegen fell back to nth() | Replace with a text or role filter |
| Locator overly specific | Multiple elements matched, codegen scoped it | Simplify if a single element matches without scoping |
| Authentication expires during recording | No storage state persisted | Use --save-storage and --load-storage |
| Recording misses iframe content | Codegen scopes to main frame | Use frameLocator manually after recording |
| Test name is always “test” | Codegen default | Rename to describe the scenario |
| No page object extraction | Raw recording is linear | Refactor after copying into the test file |
Real-World Examples
1. Recording against a local development server
// npx playwright codegen http://localhost:5173
await page.goto('http://localhost:5173/');
2. Saving authentication state during recording
// npx playwright codegen --save-storage=auth.json https://app.example.com
await page.getByLabel('Email').fill('user@example.com');
3. Recording with device emulation
// npx playwright codegen --device="iPhone 13" https://mobile.example.com
await page.getByRole('button', { name: 'Menu' }).click();
4. Recording in dark mode
// npx playwright codegen --color-scheme=dark https://example.com
await expect(page.getByText('Dark theme active')).toBeVisible();
5. Recording with a specific viewport
// npx playwright codegen --viewport-size="1920,1080" https://example.com
await page.getByRole('link', { name: 'Dashboard' }).click();
6. Recording a login flow for later reuse
await page.getByLabel('Username').fill('testuser');
await page.getByLabel('Password').fill('securepass');
await page.getByRole('button', { name: 'Sign in' }).click();
7. Recording a form submission with assertion
await page.getByLabel('Full name').fill('Jane Doe');
await page.getByRole('button', { name: 'Submit' }).click();
await expect(page.getByText('Thank you')).toBeVisible();
8. Using Pick Locator for a table cell
// Hover and click the cell in the browser to generate:
page.getByRole('cell', { name: 'Active' });
9. Recording with geolocation emulation
// npx playwright codegen --geolocation="40.7128,-74.0060" https://maps.example.com
await expect(page.getByText('New York')).toBeVisible();
10. Recording navigation between pages
await page.getByRole('link', { name: 'Settings' }).click();
await page.getByRole('link', { name: 'Profile' }).click();
Visual
The Codegen Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CODEGEN LAUNCH โ
โ โ
โ npx playwright codegen <URL> โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โ
โ โ Browser โโโโโโโบโ Playwright โ โ
โ โ Window โ โ Inspector โ โ
โ โ โ โ โ โ
โ โ You click, โ โ Code appears โ โ
โ โ fill, press โ โ line by line โ โ
โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โ
โ โ โ โ
โ โ โผ โ
โ โ โโโโโโโโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโโบโ Generated โ โ
โ actions โ TypeScript โ โ
โ โ test code โ โ
โ โโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Locator Priority Ladder
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ HOW CODEGEN CHOOSES A LOCATOR โ
โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ 1. getByRole โ โ
โ โ Accessible role + name โ โ
โ โ Most resilient, user-facing โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ falls through if no match โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ 2. getByLabel / getByPlaceholder / getByTextโ โ
โ โ Associated label or visible text โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ 3. getByTestId โ โ
โ โ Explicit data-testid attribute โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ 4. CSS / XPath (fallback, avoid) โ โ
โ โ Structural, fragile โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Recording-to-Test Pipeline
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ FROM RECORDING TO MAINTAINABLE TEST โ
โ โ
โ [Record] โโโบ [Copy] โโโบ [Paste] โโโบ [Refine] โ
โ โ
โ Record: Actions in browser โ
โ Copy: Inspector โ clipboard โ
โ Paste: Into a .spec.ts file โ
โ Refine: โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โข Add missing assertions โ โ
โ โ โข Simplify nth() locators โ โ
โ โ โข Rename the test โ โ
โ โ โข Extract page objects โ โ
โ โ โข Remove hardcoded waits โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ The recording is the skeleton. โ
โ The refinement is the test. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Command | npx playwright codegen <URL> |
| Windows opened | Browser + Playwright Inspector |
| Default browser | Chromium |
| Locator priority | Role โ Label/Text โ Test ID โ CSS |
| Assertion buttons | Visibility, Text, Value |
| Locator Picker | Hover to see, click to select |
| Storage state | --save-storage / --load-storage |
| Emulation options | --device, --viewport-size, --color-scheme, --geolocation |
| Output language | TypeScript by default (configurable) |
| Limitation | Actions only; assertions must be explicitly added |
Key takeaways:
- Codegen records actions, not intent. The generated test performs clicks and fills but verifies nothing unless you use the assertion toolbar. Treat every raw recording as incomplete until assertions are added.
- Locator priority is the real lesson. Watching Codegen choose locators teaches Playwright’s stability hierarchy: accessible roles first, then labels and text, then test IDs, and structural selectors only as a last resort.
- Pick Locator is a learning tool. Even when not recording a full test, the Pick Locator button demonstrates which selector Playwright would use for any element on the page.
- Authentication state eliminates repetition. Use
--save-storageonce after logging in, then--load-storagefor every subsequent recording session to skip the login flow. - Emulation options match test configuration. Recording under the same viewport, device, and color scheme as your CI configuration ensures the generated locators are valid under production conditions.
- Raw recordings require refinement. The generated code is a transcript, not a test. Rename it, simplify over-specific locators, add missing assertions, and extract repeated patterns before committing.
nth()chains are a warning sign. When Codegen falls back to.nth(2), it means no unique accessible identifier exists. Investigate whether a better locatorโor a test IDโcan be added to the application.
Remember: Playwright Codegen is a bridge between manual exploration and automated verification. It lowers the barrier to writing the first test by eliminating the blank-page problem: instead of staring at an empty editor wondering how to locate a button, you click the button and watch the locator appear. But the recorder cannot know what you intend to verify, cannot distinguish a stable selector from a fragile one, and cannot structure your test for maintainability. Those responsibilities remain yours. Use Codegen to generate the skeleton, then apply the judgmentโassertions, simplification, and structureโthat transforms a recording into a test worth running.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!