Playwright CLI

The Complete Guide for QA Engineers - From Installation to Mastery. Learn the standard CLI, the new @playwright/cli for AI agents, and how they compare to MCP.

Beginner Friendly Hands-On Projects AI Agent Integration Interview Ready

1 What is Playwright CLI?

The command-line interface that powers Playwright testing workflows

Playwright CLI is the command-line toolset for Microsoft Playwright - the modern browser automation framework. It lets you run tests, record tests via codegen, debug with inspector, view traces, manage browsers, and generate reports - all from your terminal.

Key Fact: As of 2026, there are TWO Playwright CLI tools. The standard npx playwright that ships with @playwright/test, and the new @playwright/cli package built specifically for AI coding agents.

Why QA Engineers Need Playwright CLI

Speed

Run tests, filter by grep, retry failures, and shard across machines - all from a single terminal command. No GUI needed.

Codegen

Record browser interactions and auto-generate test scripts in JS, TS, Python, Java, or C#. Fastest way to bootstrap tests.

CI/CD Native

CLI commands integrate directly into GitHub Actions, Jenkins, GitLab CI. No special plugins required.

2 Two CLIs - Standard vs @playwright/cli

Understanding the two different tools and when to use each

Standard CLI (npx playwright)

Purpose: Running test suites, codegen, debugging, reports

Package: Ships with @playwright/test

Best for: Traditional QA workflows, CI/CD pipelines

# Installation
npm init playwright@latest
npx playwright install

# Common commands
npx playwright test
npx playwright codegen https://example.com
npx playwright show-report
npx playwright test --debug

New @playwright/cli (AI Agent CLI)

Purpose: Browser automation for AI coding agents

Package: Separate @playwright/cli package

Best for: Claude Code, Cursor, Copilot, Windsurf integration

# Installation
npm install -g @playwright/cli@latest
playwright-cli install
playwright-cli install --skills

# Common commands
playwright-cli open https://example.com
playwright-cli snapshot
playwright-cli click e15
playwright-cli fill e22 "hello"
+----------------------------------+ +----------------------------------+ | Standard Playwright CLI | | @playwright/cli (New) | |----------------------------------| |----------------------------------| | npx playwright test | | playwright-cli open URL | | npx playwright codegen | | playwright-cli snapshot | | npx playwright show-report | | playwright-cli click ref | | npx playwright show-trace | | playwright-cli fill ref "text" | | npx playwright install | | playwright-cli screenshot | | | | | | Test Runner + Codegen | | Interactive Browser Control | | CI/CD Focused | | AI Agent Focused | | One-shot execution | | Persistent daemon sessions | +----------------------------------+ +----------------------------------+

3 Installation Guide

Step-by-step setup for both CLIs

Standard Playwright CLI

  1. Initialize a new Playwright project
    npm init playwright@latest

    This creates playwright.config.ts, sample tests, and a GitHub Actions workflow.

  2. Install browsers
    # Install all browsers
    npx playwright install
    
    # Install with OS dependencies (for CI)
    npx playwright install --with-deps
    
    # Install only Chromium
    npx playwright install chromium
  3. Verify installation
    npx playwright --version
    npx playwright test --list

@playwright/cli for AI Agents

  1. Install globally
    npm install -g @playwright/cli@latest
  2. Install browser binaries
    playwright-cli install
  3. Install Skills (for AI agent discovery)
    playwright-cli install --skills

    This creates .claude/skills/playwright-cli/SKILL.md for automatic discovery by Claude Code and compatible agents.

  4. Verify
    playwright-cli --version
    playwright-cli open https://example.com

Full Setup Script (Both CLIs)

#!/bin/bash
# 1. Standard Playwright
npm init playwright@latest
npx playwright install --with-deps

# 2. New @playwright/cli
npm install -g @playwright/cli@latest
playwright-cli install
playwright-cli install --skills

# 3. Verify both
echo "Standard CLI:"
npx playwright --version
echo "@playwright/cli:"
playwright-cli --version
Prerequisites: Node.js 18+ and npm 9+. Run node --version to check.

4 All CLI Commands & Flags

Complete command reference for both CLIs

Standard CLI Commands

Command Purpose Example
npx playwright testRun all testsnpx playwright test
test --headedRun in visible browsernpx playwright test --headed
test --debugDebug with Inspectornpx playwright test --debug
test --uiInteractive UI modenpx playwright test --ui
test --grepFilter tests by namenpx playwright test --grep "login"
test --projectRun specific browsernpx playwright test --project=chromium
test --workersParallel workersnpx playwright test --workers=4
test --retriesRetry failed testsnpx playwright test --retries=2
test --trace onRecord tracesnpx playwright test --trace on
test --shardShard across machinesnpx playwright test --shard=1/3
codegenRecord testsnpx playwright codegen https://app.vwo.com
show-reportView HTML reportnpx playwright show-report
show-traceView trace filenpx playwright show-trace trace.zip
installInstall browsersnpx playwright install chromium
clear-cacheClear browser cachenpx playwright clear-cache

Codegen Flags

FlagPurposeExample
--targetLanguage output--target javascript / python / java / csharp
--outputSave to file--output tests/login.spec.js
--browserBrowser to use--browser firefox
--deviceEmulate device--device "iPhone 13"
--viewport-sizeSet viewport--viewport-size "1280,720"
--color-schemeDark/light mode--color-scheme dark
--save-storageSave auth state--save-storage auth.json
--load-storageLoad auth state--load-storage auth.json

@playwright/cli Commands (AI Agent CLI)

CategoryCommands
Browseropen, close, goto, reload
Interactionclick, fill, type, drag, select, check, uncheck
Inspectionsnapshot, screenshot, pdf, eval, console, network
Keyboardpress, mousemove, mousewheel
Storagestate-save, state-load, cookie-list, localstorage-list
Tracingtracing-start, tracing-stop, video-start, video-stop
Sessionlist, close-all, kill-all

5 Codegen - Recording Tests

The fastest way to create Playwright tests

Run codegen
Interact with browser
Code auto-generated
Copy/Save test
# Basic codegen
npx playwright codegen https://app.vwo.com

# Generate Python test
npx playwright codegen --target python https://app.vwo.com

# Save directly to file
npx playwright codegen --output tests/login.spec.js https://app.vwo.com

# Emulate iPhone 13
npx playwright codegen --device "iPhone 13" https://app.vwo.com

# Dark mode + timezone
npx playwright codegen --color-scheme dark --timezone "Asia/Kolkata" https://app.vwo.com

# Save authentication state after login
npx playwright codegen --save-storage auth.json https://app.vwo.com

# Reuse saved auth in next session
npx playwright codegen --load-storage auth.json https://app.vwo.com

How Codegen Generates Locators

Codegen automatically picks the most resilient locator strategy, in this order of priority:

PriorityStrategyExample
1Role-basedgetByRole('button', { name: 'Login' })
2Text-basedgetByText('Welcome back')
3Test IDgetByTestId('login-btn')
4PlaceholdergetByPlaceholder('Enter email')
5CSS Selectorlocator('#login-form input')

6 MCP vs CLI - Complete Comparison

When to use Playwright MCP Server vs the CLI tool

AspectPlaywright MCP ServerPlaywright CLI@playwright/cli (New)
Architecture JSON-RPC over stdio/SSE, runs inside AI agent process Standard CLI, one-shot execution per command Client-daemon over Unix sockets, persistent sessions
Token Usage ~115K tokens per 30 actions (snapshots in context) N/A (not used with AI agents) ~25K tokens per 30 actions (snapshots to disk, 4.6x savings)
Setup Add to MCP config (settings.json), auto-starts npm init playwright@latest npm i -g @playwright/cli + skills install
Browser Lifetime Managed by MCP server, per-tool-call Starts/stops per command Persistent daemon, survives between commands
Best For AI agents doing interactive testing, live exploration CI/CD, manual test runs, codegen, reports AI agents needing token-efficient browser automation
IDE Support Claude Code, Cursor, Windsurf (via MCP config) VS Code Extension, any terminal Claude Code, Cursor, Copilot, Windsurf (via skills)
Codegen No built-in codegen Full codegen with Inspector UI YAML flow logging, auto-generates code
Multi-browser One browser per session Parallel via --project and --shard Named sessions, parallel instances
Tracing Supported via tool calls --trace on flag tracing-start / tracing-stop
Network Mocking Not directly supported Via test code (page.route) route command

Decision Matrix: Which Tool to Use?

Use Standard CLI When:

  • Running tests in CI/CD
  • Recording tests with codegen
  • Viewing reports and traces
  • Manual QA workflows
  • Installing/managing browsers

Use MCP Server When:

  • AI agent needs live browser access
  • Interactive test exploration
  • Context window is not a concern
  • Already using MCP infrastructure
  • Need rich snapshot data in-context

Use @playwright/cli When:

  • AI agent needs token efficiency
  • Persistent browser sessions needed
  • Complex multi-step automation
  • Network mocking required
  • State save/restore workflows

7 IDE & AI Tool Integration

Setting up Playwright CLI across VS Code, Claude Code, Codex, Cursor, and Windsurf

VS Code - Playwright Test Extension

  1. Install the extension

    Search for "Playwright Test for VS Code" in the Extensions panel and install it.

  2. Key Features
    • Record New: Click "Record New" in the Testing sidebar to open a browser and generate a test file while you interact.
    • Record at Cursor: Place your cursor in an existing test and click "Record at Cursor" to append new actions.
    • Pick Locator: Hover over elements in the browser to see locators, click to copy.
    • Show Trace: Right-click a test result to view its trace inline.
  3. Run from Terminal
    # All standard CLI commands work in VS Code terminal
    npx playwright test --headed
    npx playwright codegen https://app.vwo.com
    npx playwright show-report

Claude Code Integration

Claude Code supports Playwright via two methods: MCP Server and @playwright/cli Skills.

Method 1: MCP Server (in settings.json)

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest"]
    }
  }
}

This gives Claude Code direct browser_snapshot, browser_click, browser_type etc. tools.

Method 2: @playwright/cli with Skills

# Install CLI + skills
npm install -g @playwright/cli@latest
playwright-cli install --skills

# This creates .claude/skills/playwright-cli/SKILL.md
# Claude Code auto-discovers and uses it

Method 3: Custom Skill File

Create your own skill (see Skill File section below) to customize how Claude Code uses the CLI.

Cursor Integration

  1. MCP Config

    Open Cursor Settings > MCP and add:

    {
      "mcpServers": {
        "playwright": {
          "command": "npx",
          "args": ["@playwright/mcp@latest"]
        }
      }
    }
  2. @playwright/cli Skills
    npm install -g @playwright/cli@latest
    playwright-cli install --skills

    Cursor's AI composer auto-detects the skill file in .cursor/skills/ or .claude/skills/.

  3. Terminal commands
    # Use standard CLI in Cursor's terminal
    npx playwright test --headed
    npx playwright codegen https://app.vwo.com

Windsurf (Codeium) Integration

  1. MCP Server Setup

    Add to Windsurf's MCP configuration:

    {
      "mcpServers": {
        "playwright": {
          "command": "npx",
          "args": ["@playwright/mcp@latest"]
        }
      }
    }
  2. @playwright/cli
    npm install -g @playwright/cli@latest
    playwright-cli install --skills

    Windsurf's Cascade AI detects skills and offers browser automation commands.

  3. Use in Chat

    Ask Cascade: "Open app.vwo.com and record a login test" - it will use the detected Playwright CLI tools.

OpenAI Codex CLI Integration

  1. Setup

    Codex CLI works with terminal commands. Install both CLIs:

    npm init playwright@latest
    npm install -g @playwright/cli@latest
  2. Usage

    Ask Codex to generate and run Playwright CLI commands:

    # Example Codex prompts:
    "Generate a Playwright test for app.vwo.com login"
    "Run my Playwright tests with retries"
    "Record a codegen session for the checkout flow"
  3. Integration

    Codex reads your playwright.config.js and test files to understand your project structure. It can generate npx playwright commands directly.

8 Three Hands-On Projects

Complete walkthroughs with code samples

Project 1: Automate Login on app.vwo.com using Playwright CLI

Beginner Codegen + Manual

Objective

Use Playwright CLI codegen to record a login flow on app.vwo.com, then refine the generated test into a production-ready spec file.

Step 1: Record with Codegen

# Open codegen targeting app.vwo.com
npx playwright codegen https://app.vwo.com

# Save output directly to a file
npx playwright codegen --output tests/vwo_login.spec.js https://app.vwo.com
During recording: Navigate to app.vwo.com, enter your email, enter your password, click Sign In. The Inspector window shows the generated code in real-time.

Step 2: Generated Code (Typical Output)

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

test('VWO Login Test', async ({ page }) => {
  // Navigate to VWO login page
  await page.goto('https://app.vwo.com');

  // Fill email field
  await page.getByPlaceholder('e.g. [email protected]')
    .fill('[email protected]');

  // Fill password field
  await page.getByPlaceholder('Enter password')
    .fill('your_password_here');

  // Click Sign In button
  await page.getByRole('button', { name: 'Sign in to VWO' })
    .click();

  // Assert successful login - dashboard is visible
  await expect(page).toHaveURL(/dashboard/);
});

Step 3: Refine into Framework Pattern

// tests/vwo_login.spec.js - Production-ready version
import { test, expect } from '@playwright/test';

// Test data (move to .env or config in real projects)
const LOGIN_URL = 'https://app.vwo.com';
const VALID_EMAIL = process.env.VWO_EMAIL || '[email protected]';
const VALID_PASS = process.env.VWO_PASS || 'TestPass123';

test.describe('VWO Login Suite', () => {

  test.beforeEach(async ({ page }) => {
    await page.goto(LOGIN_URL);
  });

  test('TC-001: Successful login with valid credentials',
    async ({ page }) => {
      await page.getByPlaceholder('e.g. [email protected]')
        .fill(VALID_EMAIL);
      await page.getByPlaceholder('Enter password')
        .fill(VALID_PASS);
      await page.getByRole('button', { name: 'Sign in to VWO' })
        .click();
      await expect(page).toHaveURL(/dashboard/);
  });

  test('TC-002: Login fails with invalid password',
    async ({ page }) => {
      await page.getByPlaceholder('e.g. [email protected]')
        .fill(VALID_EMAIL);
      await page.getByPlaceholder('Enter password')
        .fill('WrongPassword');
      await page.getByRole('button', { name: 'Sign in to VWO' })
        .click();
      await expect(
        page.getByText('Your email or password is incorrect')
      ).toBeVisible();
  });

  test('TC-003: Login fails with empty fields',
    async ({ page }) => {
      await page.getByRole('button', { name: 'Sign in to VWO' })
        .click();
      // Verify validation error appears
      await expect(
        page.getByText('required')
      ).toBeVisible();
  });
});

Step 4: Run the Tests

# Run all login tests
npx playwright test tests/vwo_login.spec.js --headed

# Run with trace for debugging
npx playwright test tests/vwo_login.spec.js --trace on

# Run on specific browser
npx playwright test tests/vwo_login.spec.js --project=chromium

# Debug mode with Inspector
npx playwright test tests/vwo_login.spec.js --debug

Project 2: Generate E2E Test Suite with Codegen

Intermediate Full Suite

Objective

Use codegen to generate a complete E2E test suite for the-internet.herokuapp.com covering multiple pages, then run with reporting and tracing.

Step 1: Record Multiple Flows

# Record form authentication flow
npx playwright codegen \
  --output tests/auth.spec.js \
  https://the-internet.herokuapp.com/login

# Record dropdown interaction
npx playwright codegen \
  --output tests/dropdown.spec.js \
  https://the-internet.herokuapp.com/dropdown

# Record checkbox interactions
npx playwright codegen \
  --output tests/checkboxes.spec.js \
  https://the-internet.herokuapp.com/checkboxes

# Record on mobile viewport
npx playwright codegen \
  --device "iPhone 13" \
  --output tests/mobile_nav.spec.js \
  https://the-internet.herokuapp.com

Step 2: Save Auth State for Reuse

# Login once, save state
npx playwright codegen \
  --save-storage auth-state.json \
  https://the-internet.herokuapp.com/login

# Now use saved state in future codegen sessions
npx playwright codegen \
  --load-storage auth-state.json \
  https://the-internet.herokuapp.com/secure

Step 3: Configure and Run Full Suite

// playwright.config.js
module.exports = {
  testDir: './tests',
  timeout: 30000,
  retries: 1,
  workers: 3,
  reporter: [
    ['html', { open: 'never' }],
    ['json', { outputFile: 'reports/results.json' }]
  ],
  use: {
    baseURL: 'https://the-internet.herokuapp.com',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },
  projects: [
    { name: 'chromium', use: { browserName: 'chromium' } },
    { name: 'firefox', use: { browserName: 'firefox' } },
    { name: 'webkit', use: { browserName: 'webkit' } },
  ],
};
# Run full suite across all browsers
npx playwright test

# View the HTML report
npx playwright show-report

# Run only auth tests with retries
npx playwright test --grep "auth" --retries=2

# Shard across 3 CI machines
npx playwright test --shard=1/3
npx playwright test --shard=2/3
npx playwright test --shard=3/3

Project 3: AI Agent + Playwright CLI Workflow

Advanced AI Integration

Objective

Use @playwright/cli with an AI agent (Claude Code) to interactively automate and test a web application with persistent sessions and token-efficient snapshots.

Step 1: Setup @playwright/cli with Skills

# Install and setup
npm install -g @playwright/cli@latest
playwright-cli install
playwright-cli install --skills

# Verify skill file was created
cat .claude/skills/playwright-cli/SKILL.md

Step 2: Interactive Session (via Claude Code or Terminal)

# Open a persistent session
playwright-cli open https://app.vwo.com -s=vwo-login --persistent

# Take an accessibility snapshot (saved to disk, not stdout)
playwright-cli snapshot -s=vwo-login

# Fill the email field (using snapshot ref e.g., e15)
playwright-cli fill e15 "[email protected]" -s=vwo-login

# Fill password (ref e22 from snapshot)
playwright-cli fill e22 "MyPassword123" -s=vwo-login

# Click the Sign In button (ref e28)
playwright-cli click e28 -s=vwo-login

# Take a screenshot to verify
playwright-cli screenshot -s=vwo-login

# Save auth state for reuse
playwright-cli state-save vwo-auth.json -s=vwo-login

# Start tracing for debugging
playwright-cli tracing-start -s=vwo-login

# ... do more actions ...

# Stop tracing and save
playwright-cli tracing-stop -s=vwo-login --output trace.zip

Step 3: AI Agent Workflow Example

// Example: What happens when you tell Claude Code
// "Login to app.vwo.com and verify the dashboard loads"

// Claude Code with @playwright/cli skill will:
// 1. Run: playwright-cli open https://app.vwo.com -s=test
// 2. Run: playwright-cli snapshot -s=test
// 3. Read snapshot file (25K tokens vs 115K with MCP)
// 4. Identify email field ref, fill it
// 5. Identify password field ref, fill it
// 6. Click sign-in button ref
// 7. Take screenshot to verify dashboard
// 8. Report results back to you

MCP vs CLI Token Comparison

30-action login automation flow: MCP Server: |████████████████████████████████████████████████| ~115,000 tokens @playwright/cli: |██████████| ~25,000 tokens Savings: 4.6x fewer tokens = Faster responses + Lower cost

9 10 Exercises for Practice

Hands-on tasks to build your Playwright CLI mastery

Exercise 1: Your First CLI Test Run

Task: Create a basic Playwright project and run the sample tests.

mkdir my-pw-project && cd my-pw-project
npm init playwright@latest
npx playwright test
npx playwright show-report

Expected: See test results in terminal and HTML report opens in browser.

Exercise 2: Record a Google Search Test

Task: Use codegen to record a test that searches Google for "Playwright testing" and verifies results appear.

npx playwright codegen --output tests/google.spec.js https://google.com

Steps: Type in search box, press Enter, verify results. Save and run.

Exercise 3: Multi-Browser Test Execution

Task: Run your tests on Chromium, Firefox, and WebKit using CLI flags.

# Run on each individually
npx playwright test --project=chromium
npx playwright test --project=firefox
npx playwright test --project=webkit

# Run all three at once
npx playwright test

Expected: Compare results across all three browsers.

Exercise 4: Codegen with Device Emulation

Task: Record a mobile test on iPhone 13 and iPad Pro.

npx playwright codegen --device "iPhone 13" https://example.com
npx playwright codegen --device "iPad Pro 11" https://example.com

Expected: Browser opens with device viewport. Generated code includes device config.

Exercise 5: Debug a Failing Test

Task: Create an intentionally failing test, then use debug mode and trace to find the issue.

// Create a test that will fail
test('should find nonexistent element', async ({ page }) => {
  await page.goto('https://example.com');
  await expect(page.locator('#does-not-exist')).toBeVisible();
});

# Debug it
npx playwright test --debug

# Or use trace
npx playwright test --trace on
npx playwright show-trace test-results/*/trace.zip
Exercise 6: Grep and Filter Tests

Task: Create 5 tests with different names and practice filtering them.

# Run only tests with "login" in name
npx playwright test --grep "login"

# Exclude tests with "slow" in name
npx playwright test --grep-invert "slow"

# Run specific file
npx playwright test tests/auth.spec.js

# List all tests without running
npx playwright test --list
Exercise 7: Auth State Save & Reuse

Task: Use codegen to login to a site, save the auth state, then reuse it in a new session.

# Step 1: Login and save state
npx playwright codegen --save-storage auth.json https://the-internet.herokuapp.com/login

# Step 2: Use saved state (skip login)
npx playwright codegen --load-storage auth.json https://the-internet.herokuapp.com/secure
Exercise 8: CI/CD Pipeline Simulation

Task: Simulate a CI pipeline by running tests with CI-friendly flags.

# CI-style execution
npx playwright test \
  --reporter=json \
  --output-folder=ci-results \
  --workers=4 \
  --retries=2 \
  --trace=on-first-retry \
  --forbid-only

# Sharding for parallel CI jobs
npx playwright test --shard=1/3
npx playwright test --shard=2/3
npx playwright test --shard=3/3
Exercise 9: @playwright/cli Interactive Session

Task: Install @playwright/cli and automate a form fill using interactive commands.

npm install -g @playwright/cli@latest
playwright-cli install

# Open a page
playwright-cli open https://the-internet.herokuapp.com/login -s=demo

# Take snapshot to see element refs
playwright-cli snapshot -s=demo

# Fill username and password using refs from snapshot
playwright-cli fill <username-ref> "tomsmith" -s=demo
playwright-cli fill <password-ref> "SuperSecretPassword!" -s=demo
playwright-cli click <button-ref> -s=demo

# Screenshot to verify
playwright-cli screenshot -s=demo
Exercise 10: Custom Reporter + CLI Integration

Task: Create a custom reporter and use it via CLI flags.

// reporters/my-reporter.js
class MyReporter {
  onBegin(config, suite) {
    console.log(`Starting ${suite.allTests().length} tests`);
  }
  onTestEnd(test, result) {
    console.log(`${result.status}: ${test.title}`);
  }
  onEnd(result) {
    console.log(`Finished: ${result.status}`);
  }
}
module.exports = MyReporter;

# Use via CLI
npx playwright test --reporter=./reporters/my-reporter.js

10 Quiz - Test Your Knowledge

10 questions to check your understanding

Q1: Which command records browser interactions and generates test code?

  • a) npx playwright test --record
  • b) npx playwright codegen
  • c) npx playwright generate
  • d) npx playwright capture
Answer: b) npx playwright codegen [url] opens a browser and the Playwright Inspector, generating code as you interact.

Q2: What is the primary advantage of @playwright/cli over MCP for AI agents?

  • a) More browser support
  • b) ~4.6x token reduction (snapshots to disk)
  • c) Faster browser launch
  • d) Better CSS selectors
Answer: b) @playwright/cli writes snapshots to disk instead of streaming them into the model's context, using ~25K tokens vs ~115K for a 30-action flow.

Q3: Which flag runs tests in a visible browser window?

  • a) --visible
  • b) --show
  • c) --headed
  • d) --gui
Answer: c) npx playwright test --headed runs tests in headed (visible) mode.

Q4: How do you save authentication state with codegen?

  • a) --auth-file auth.json
  • b) --save-storage auth.json
  • c) --save-cookies auth.json
  • d) --persist auth.json
Answer: b) --save-storage auth.json saves cookies, localStorage, and sessionStorage.

Q5: What is the architecture of @playwright/cli?

  • a) HTTP REST API
  • b) Client-daemon over Unix sockets
  • c) WebSocket server
  • d) gRPC protocol
Answer: b) @playwright/cli uses a client-daemon architecture where commands travel over Unix sockets and browsers persist between calls.

Q6: Which command opens the interactive test runner in VS Code?

  • a) npx playwright test --ui
  • b) npx playwright test --interactive
  • c) npx playwright test --vscode
  • d) npx playwright ui
Answer: a) --ui opens the Playwright UI Mode for interactive test running and debugging.

Q7: How do you run tests on only Firefox using CLI?

  • a) npx playwright test --browser=firefox
  • b) npx playwright test --project=firefox
  • c) npx playwright test --firefox
  • d) npx playwright test --only-firefox
Answer: b) --project=firefox runs tests on the Firefox project as defined in playwright.config.

Q8: What does the codegen --target python flag do?

  • a) Runs the recorded test in Python
  • b) Generates the recorded code in Python syntax
  • c) Uses Python to control the browser
  • d) Converts existing JS tests to Python
Answer: b) --target python generates the recorded interactions as Python code (using pytest-playwright syntax).

Q9: In @playwright/cli, what does the -s flag specify?

  • a) Selector strategy
  • b) Session name
  • c) Screenshot output
  • d) Speed setting
Answer: b) -s=name specifies a named session. Multiple sessions can run in parallel.

Q10: Which locator strategy does Playwright codegen prioritize first?

  • a) CSS selectors
  • b) XPath
  • c) Role-based (getByRole)
  • d) Test ID (getByTestId)
Answer: c) Codegen prioritizes getByRole first, then getByText, then getByTestId, then CSS selectors.

11 10 Interview Questions & Answers

Commonly asked Playwright CLI questions in QA interviews

1. What is Playwright CLI and how does it differ from Playwright as a library?

Answer: Playwright CLI is the command-line interface that ships with the @playwright/test package. While Playwright as a library provides APIs to write test scripts programmatically (page.goto, page.click, etc.), the CLI provides tools to run those tests (npx playwright test), record new tests (codegen), debug them (--debug), view reports (show-report), and manage browsers (install). The CLI is the operational layer on top of the library.

2. Explain the Playwright codegen tool and its use cases.

Answer: npx playwright codegen [url] opens a browser and the Playwright Inspector side by side. As you interact with the browser (click, type, navigate), the Inspector generates test code in real-time. Use cases include: rapid test prototyping, discovering correct locators for complex UIs, generating tests in multiple languages (JS, Python, Java, C#), testing mobile viewports via --device flag, and saving auth state via --save-storage for reuse.

3. How do you run Playwright tests across multiple browsers?

Answer: Define projects in playwright.config.js for each browser (chromium, firefox, webkit). Then run npx playwright test to execute on all, or npx playwright test --project=chromium for a specific one. For CI, use sharding: --shard=1/3, --shard=2/3, --shard=3/3 to distribute tests across parallel machines.

4. What is the difference between --headed, --debug, and --ui modes?

Answer:

  • --headed: Runs tests with a visible browser window. Tests execute at full speed. Good for watching test execution.
  • --debug: Opens Playwright Inspector alongside the browser. Tests pause at each step, letting you step through, inspect locators, and evaluate expressions. Best for debugging failures.
  • --ui: Opens an interactive web UI with a test list, timeline, trace viewer, and source code view. You can run, filter, and watch tests. Best for development workflow.
5. How do you handle test retries and flaky tests with Playwright CLI?

Answer: Use npx playwright test --retries=2 to retry failed tests up to 2 times. Combine with --trace on-first-retry to capture traces only when a retry happens (saving disk space). In CI, use --reporter=json to track flaky test patterns. The --forbid-only flag prevents accidentally committed test.only from running in CI.

6. Explain the Playwright Trace Viewer and how to use it.

Answer: The Trace Viewer is a post-mortem debugging tool. Record traces with npx playwright test --trace on. View with npx playwright show-trace trace.zip. It shows: a timeline of every action, DOM snapshots before/after each action, network requests, console logs, and test source code. It is essential for debugging CI failures where you cannot reproduce locally.

7. What is @playwright/cli and how does it compare to the standard CLI?

Answer: @playwright/cli is a separate npm package purpose-built for AI coding agents (Claude Code, Cursor, Copilot). Key differences: (1) Uses client-daemon architecture with persistent browser sessions vs one-shot execution. (2) Writes snapshots to disk (~4.6x token reduction vs MCP). (3) Supports named sessions via -s flag for parallel automation. (4) Has 50+ interactive commands (click, fill, snapshot) vs the standard CLI's test-runner focus. Choose standard CLI for CI/CD test runs, @playwright/cli for AI agent workflows.

8. How do you integrate Playwright CLI with CI/CD pipelines?

Answer: Key CI flags: --reporter=json,html for machine-readable + human-readable output; --workers=4 for parallelism; --retries=2 for flaky test resilience; --shard=1/N for distributing across N machines; --forbid-only to prevent test.only leaks. For Docker: npx playwright install --with-deps installs browser + OS dependencies. GitHub Actions has a dedicated playwright action for caching browsers.

9. What is Playwright MCP and when would you use it vs the CLI?

Answer: Playwright MCP (Model Context Protocol) Server provides browser automation as tool calls within an AI agent's context. Use MCP when: the AI agent needs real-time browser state in its context window, doing interactive exploration, or already using MCP infrastructure. Use CLI when: running in CI/CD, recording tests with codegen, viewing reports/traces, or when token efficiency matters (@playwright/cli uses 4.6x fewer tokens than MCP).

10. How does Playwright codegen choose locator strategies?

Answer: Codegen uses a priority-based locator selection: (1) getByRole - most resilient, uses ARIA roles; (2) getByText - visible text content; (3) getByTestId - data-testid attributes; (4) getByPlaceholder - input placeholders; (5) CSS selectors - last resort. This hierarchy produces tests that are less brittle and more maintainable. The VS Code extension's "Pick Locator" feature uses the same algorithm to suggest locators on hover.

12 Playwright CLI Skill File

Ready-to-use skill for Claude Code / AI agents

How to Install

# Create the skill directory
mkdir -p .claude/skills/playwright-cli

# Copy the SKILL.md content below into this file:
# .claude/skills/playwright-cli/SKILL.md

SKILL.md Content

---
name: playwright-cli
description: >
  Automate browser interactions using Playwright CLI tools.
  Covers both standard CLI (npx playwright) for test execution,
  codegen, debugging, reporting, and the new @playwright/cli
  for AI-agent-friendly persistent browser sessions.
triggers:
  - playwright
  - codegen
  - browser test
  - e2e test
  - record test
  - login automation
  - headed mode
  - trace viewer
  - html report
---

# Playwright CLI Skill

## Standard CLI Commands (npx playwright)

### Run Tests
```bash
npx playwright test                         # Run all tests
npx playwright test --headed                # Visible browser
npx playwright test --debug                 # Debug with Inspector
npx playwright test --ui                    # Interactive UI mode
npx playwright test --grep "login"          # Filter by name
npx playwright test --project=chromium      # Specific browser
npx playwright test --workers=4             # Parallel execution
npx playwright test --retries=2             # Retry failures
npx playwright test --trace on              # Record traces
npx playwright test --shard=1/3             # Shard for CI
npx playwright test --list                  # List tests (no run)
```

### Record Tests (Codegen)
```bash
npx playwright codegen [url]                       # Record test
npx playwright codegen --output tests/my.spec.js   # Save to file
npx playwright codegen --target python              # Python output
npx playwright codegen --device "iPhone 13"         # Mobile
npx playwright codegen --save-storage auth.json     # Save auth
npx playwright codegen --load-storage auth.json     # Reuse auth
```

### Reports & Debugging
```bash
npx playwright show-report                 # Open HTML report
npx playwright show-trace trace.zip        # View trace file
npx playwright install                     # Install browsers
npx playwright install --with-deps         # + OS dependencies
npx playwright clear-cache                 # Clear browser cache
```

## @playwright/cli (AI Agent CLI)

### Setup
```bash
npm install -g @playwright/cli@latest
playwright-cli install
playwright-cli install --skills
```

### Interactive Commands
```bash
playwright-cli open [url] -s=[session]     # Open page
playwright-cli snapshot -s=[session]       # A11y snapshot
playwright-cli screenshot -s=[session]     # Screenshot
playwright-cli click [ref] -s=[session]    # Click element
playwright-cli fill [ref] "text" -s=[s]    # Fill input
playwright-cli type [ref] "text" -s=[s]    # Type text
playwright-cli press Enter -s=[session]    # Press key
playwright-cli select [ref] "val" -s=[s]   # Select option
playwright-cli state-save file.json -s=[s] # Save state
playwright-cli state-load file.json -s=[s] # Load state
playwright-cli close -s=[session]          # Close page
```

## Locator Priority (Codegen)
1. getByRole('button', { name: '...' })
2. getByText('...')
3. getByTestId('...')
4. getByPlaceholder('...')
5. CSS selectors (last resort)

## Common Patterns

### Login Automation
```javascript
test('login test', async ({ page }) => {
  await page.goto('https://app.example.com');
  await page.getByPlaceholder('Email').fill('[email protected]');
  await page.getByPlaceholder('Password').fill('pass123');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page).toHaveURL(/dashboard/);
});
```

### CI/CD Configuration
```bash
npx playwright test \
  --reporter=json,html \
  --workers=4 \
  --retries=2 \
  --trace=on-first-retry \
  --forbid-only
```