</>

Technology

Playwright

Difficulty

Beginner

Interview Question

What is the Playwright codegen tool and how do you use it?

Answer

Playwright Codegen — Auto Test Generation

Codegen is a built-in test recorder that opens a browser window and records your interactions — generating test code automatically in real time.

Basic Usage

Bash
npx playwright codegen https://example.com

This opens:

  1. A browser window — you interact with the site normally
  2. A Playwright Inspector window — shows generated code in real time

Codegen Output Example

If you visit a login page, type credentials, and click Login, codegen generates:

TypeScript
import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
  await page.goto('https://myapp.com/login');
  await page.getByLabel('Email').click();
  await page.getByLabel('Email').fill('user@example.com');
  await page.getByLabel('Password').fill('password123');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page).toHaveURL('https://myapp.com/dashboard');
});

Codegen Options

Bash
# Record in TypeScript (default)
npx playwright codegen --lang=ts https://myapp.com

# Record in JavaScript
npx playwright codegen --lang=js https://myapp.com

# Record in Python
npx playwright codegen --lang=python https://myapp.com

# Record in Java
npx playwright codegen --lang=java https://myapp.com

# Save generated code to a file
npx playwright codegen --output tests/recorded.spec.ts https://myapp.com

# Emulate a specific device
npx playwright codegen --device "iPhone 12" https://myapp.com

# Emulate viewport
npx playwright codegen --viewport-size=1280,720 https://myapp.com

# Set browser
npx playwright codegen --browser firefox https://myapp.com

How Codegen Picks Locators

Codegen prioritizes in this order:

  1. getByRole() — ARIA role
  2. getByText() — visible text
  3. getByLabel() — form labels
  4. getByTestId() — data-testid
  5. CSS selector — fallback

Tips for Using Codegen

  • Start from codegen, don't ship it — use codegen output as a starting point, then refine locators
  • Add assertions — codegen records actions but doesn't auto-add expect() checks
  • Cleanup generated code — remove unnecessary clicks/navigations from the recording
  • Use for exploration — great for quickly finding locators on an unfamiliar page

Follow AutomateQA

Related Topics