IKivan-kozenko -aqa
Try yourself as a QA tester
All topics·Beginner·12 / 16

Test generator

The full codegen reference: CLI flags for viewport/device/locale emulation, saving and loading auth state for sessions, and recording at cursor from VS Code. I use this when I need more control than the basic 'npx playwright codegen URL' — for example, recording a flow that requires being logged in, or testing on a specific device.

Recording from VS Code

With the Playwright VS Code extension installed, I can record tests directly in the editor without opening a terminal. Two modes I use regularly:

Record new — opens a new browser window and creates a new spec file. I click around in the app, assertions appear in the file, I stop recording and clean up the result.

Record at cursor — I place the cursor at a specific line inside an existing test and click Record at cursor. The browser opens at that point in the test execution and any new actions I take are inserted at the cursor position. This is useful when I want to add steps to the middle of an existing test.

Pick locator — no recording, just hover over elements to see the recommended locator. I press Enter to copy it to clipboard.

Emulation flags

I pass emulation flags directly to the codegen command when I want the recorded test to include device-specific settings. The generated test code will include the emulation settings so the test runs with the same configuration when executed.

bash
# Конкретний розмір вьюпорту
npx playwright codegen --viewport-size="1280,720" http://localhost:3000

# Емуляція мобільного пристрою (viewport + user agent)
npx playwright codegen --device="iPhone 13" http://localhost:3000/orders

# Темна кольорова схема
npx playwright codegen --color-scheme=dark http://localhost:3000

# Геолокація + часовий пояс + локаль
npx playwright codegen --timezone="Europe/Kyiv" --geolocation="50.45,30.52" --lang="uk-UA" http://localhost:3000

Recording with saved auth state

The most useful codegen workflow I've found for authenticated apps: first record a login session and save the auth state to a file. Then load that state in subsequent sessions — I start already logged in, so I can record flows that require authentication without re-logging in each time.

Important: auth.json contains cookies and localStorage — sensitive data. I always add it to .gitignore and delete it when I'm done.

bash
# Крок 1: Записати логін і зберегти стан
npx playwright codegen --save-storage=auth.json http://localhost:3000/login
# → логінюсь, закриваю браузер → auth.json містить cookies + localStorage

# Крок 2: Записати флоу починаючи вже авторизованим
npx playwright codegen --load-storage=auth.json http://localhost:3000/orders
# → відкривається вже залогована сторінка /orders
bash
# .gitignore — ніколи не комітити auth-стан
auth.json
playwright/.auth/

Recording with a custom browser setup

Sometimes I want to record actions in a browser that's already configured — with request mocking, custom headers, or a specific base URL. For this I use page.pause() in a script: Playwright opens Inspector with the Codegen panel, and I can interact and record from that pre-configured state.

ts
// record-custom.ts — запуск у headed-режимі з кастомним налаштуванням
import { chromium } from '@playwright/test'

;(async () => {
  const browser = await chromium.launch({ headless: false })
  const context = await browser.newContext({
    baseURL: 'http://localhost:3000',
    extraHTTPHeaders: { 'X-Test-Mode': 'true' },
  })

  // Перехопити запити до /api/external перед записом
  await context.route('**/api/external/**', route => route.fulfill({ json: { mocked: true } }))

  const page = await context.newPage()
  await page.goto('/orders')

  // Відкрити Inspector — тепер можна клікати і записувати
  await page.pause()

  await browser.close()
})()
bash
npx ts-node record-custom.ts

Saving generated code to a file

By default codegen copies code to the clipboard. To save directly to a file:

bash
# Зберегти прямо у spec-файл
npx playwright codegen --output=tests/orders.spec.ts http://localhost:3000/orders

# Генерувати Python-код замість TypeScript
npx playwright codegen --target=python http://localhost:3000

# Генерувати для конкретної мови
npx playwright codegen --target=java http://localhost:3000