agentic-playwright README

The project's README from github.com/idavidov13/agentic-playwright. As one markdown file: README.md.

npm create agentic-playwright — ArchQA banner, smoke test green

Agentic Playwright

Stop teaching your AI how to write tests. Hand it the rulebook.

npm Template Smoke Test Works with Claude Code, Cursor, Copilot Node >= 20 Playwright ^1.60 MIT license

Production-grade Playwright + TypeScript Scaffold for Agentic Testing.
A complete, running test framework — page objects, API contracts, data factories, CI —
plus the AI rules your assistant picks up automatically, from the very first prompt.

See it

From the (empty) directory your project should live in — the . means "scaffold right here, and name the project after this folder" (a fresh git clone of an empty repo works too). Prefer a new subfolder? Pass a name instead of .:

npm create agentic-playwright . -- --demo

Zero questions. Scaffolds the framework, installs dependencies and a browser, and ends by running the smoke test against a live demo application — you see green before writing a line. Under 5 minutes on normal broadband.

Full System Explained Live

Debbie O'Brien and Ivan Davidov will walk through the architecture at C3, "Orchestrating Agentic Test Automation with Playwright". October 21st, online, organized by Packt

Registrater here

Without the rulebook vs with it

The same prompt — "write a test for the product search" — to the same AI assistant:

// ❌ Unsupervised: XPath, hard waits, `any`, magic timeouts, no structure
test('search', async ({ page }) => {
    await page.goto('https://practicesoftwaretesting.com');
    await page.locator('//input[@id="search-query"]').fill('pliers');
    await page.locator('//button[@type="submit"]').click();
    await page.waitForTimeout(5000);
    const cards: any = await page.$$('.card');
    expect(cards.length > 0).toBe(true);
});
// ✅ With Agentic Playwright: fixtures, steps, web-first assertions
import { expect, test } from '../../../fixtures/pom/test-options';

test(
    'should show only matching products when searching',
    { tag: '@regression' },
    async ({ homePage }) => {
        await test.step('GIVEN the user is on the home page', async () => {
            await homePage.open();
        });

        await test.step('WHEN the user searches for "pliers"', async () => {
            await homePage.searchFor('pliers');
        });

        await test.step('THEN every result matches the search term', async () => {
            await expect(homePage.searchCaption).toContainText('pliers');
            await expect(homePage.productNames.first()).toContainText('Pliers');
        });
    }
);

Dependency-injected page objects, Given/When/Then steps, web-first assertions, no hard waits, no any, one tag per test — enforced by a Constitution and 17 skills the assistant loads automatically, with a write-time hook that blocks the forbidden patterns outright.

Not affiliated with Microsoft. Playwright is an open-source project by Microsoft; this scaffold builds on it.

This is a scaffold, not a finished framework. The example files (AppPage, login.spec.ts, NavigationComponent, etc.) demonstrate the patterns and conventions you should follow. Replace them with your real application's pages, tests, and data as you build out your test suite.


Table of Contents


Features

Prerequisites

Quick Start: npm create

The fastest path — scaffold a fresh project with everything wired, straight into the directory you are standing in:

npm create agentic-playwright . -- --demo

Why the .? It scaffolds into the current directory and names the project after the folder — the natural fit when you have already created (or cloned) an empty repo for your tests. The directory must be empty apart from repo bookkeeping like .git; if a git repo already exists there, the initializer detects it and skips git init. Prefer a new subfolder instead? Pass a name:

npm create agentic-playwright my-tests -- --demo  # same, but in ./my-tests
npm create agentic-playwright .                   # interactive — 4 questions
npm create agentic-playwright . -- --bare         # your own app URLs

Useful flags: --no-claude / --no-cursor / --no-copilot (prune AI rule trees you don't use), --yes, --skip-install, --skip-browsers, --skip-git, --skip-smoke.

Quick Start: Dev Container

The fastest way to get a fully working environment. Requires Docker Desktop and a Dev Containers extension for your editor:

Important: Make sure Docker Desktop is up and running before proceeding with the steps below. The Dev Container will fail to build if Docker is not started.

  1. Clone the repository:

    git clone <your-repository-url>   # replace with your fork/clone URL
    cd playwright-scaffold
    
  2. Open in Cursor/VS Code and accept the prompt to "Reopen in Container" (or run Dev Containers: Reopen in Container from the Command Palette).

  3. Done. The Docker image ships with pre-warmed npm and playwright-cli browser caches, so postCreateCommand completes in seconds even on first start. The container provides Node.js, npm dependencies (on a fast named volume), Playwright test browsers, Python 3, Claude Code CLI, and playwright/playwright-cli linked into ~/.local/bin. Edit env/.env.dev with your app configuration and run npm test.

Version alignment: The Playwright Docker image tag in .devcontainer/Dockerfile must match the @playwright/test version in package.json. When upgrading Playwright, update both.

Claude Code Custom Status Line

The scaffold includes a custom Claude Code status line that displays git branch, PR status, model, duration, cost, lines changed, and context window usage directly in the terminal.

To enable it, add the following to your .claude/settings.local.json (create the file if it doesn't exist):

{
    "statusLine": {
        "type": "command",
        "command": "python3 .claude/scripts/status_line.py"
    }
}

This renders a rich status bar at the bottom of the Claude Code terminal:

✦ main ● | 📁 project | 🤖 Sonnet 4.6 | ⏳ 12m05s | 💰 $1.42 | + 85 | — 12 | [████████░░░░] 42.5% (85,012/200k)

The status line script lives at .claude/scripts/status_line.py and uses a Gruvbox Dark color palette. It shows:

Segment Description
Git branch Current branch with dirty indicator (●)
PR status Review state emoji with clickable PR link (requires gh CLI)
Directory Current workspace folder
Model Active Claude model
Duration Session duration
Cost Cumulative API cost
Lines changed Lines added/removed in the session
Context bar Visual context window usage scaled to the autocompact threshold

Note: Cost, lines changed, and context bar segments appear dynamically as you interact with Claude Code. A fresh session will only show git, directory, model, and duration.

Quick Start: Local Setup Script

For terminal-based workflows or if you prefer not to use Docker. Works on macOS and Linux (Windows users: use WSL2).

  1. Clone the repository:

    git clone <your-repository-url>   # replace with your fork/clone URL
    cd playwright-scaffold
    
  2. Run the setup script:

    bash scripts/setup.sh
    

    This automatically installs Node.js v22 (via nvm if needed), npm dependencies, Playwright browsers with system deps, Python 3.11+, links playwright and playwright-cli into ~/.local/bin, and installs a dedicated playwright-cli Chromium cache. If you already have Node.js v22+ installed, you can also run npm run setup — it is equivalent.

  3. Ensure ~/.local/bin is on your PATH (if your shell does not already include it):

    export PATH="$HOME/.local/bin:$PATH"
    

    This is where the scaffold links playwright and playwright-cli. Add this line to your ~/.zshrc or ~/.bashrc to make it permanent.

  4. Edit env/.env.dev with your app configuration and run npm test.

Manual Installation

If you prefer to install dependencies manually. Steps 1-3 and 5-6 are identical on all platforms; step 4 differs.

  1. Clone the repository:

    git clone <your-repository-url>   # replace with your fork/clone URL
    cd playwright-scaffold
    
  2. Install npm dependencies:

    npm install
    
  3. Install Playwright test browsers:

    npx playwright install --with-deps
    
  4. Link CLI commands and install playwright-cli browsers:

    macOS / Linux:

    bash scripts/link-cli.sh "$(pwd -P)"
    npm run playwright-cli:install-browsers
    

    Then ensure ~/.local/bin is on your PATH (add to ~/.zshrc or ~/.bashrc to make permanent):

    export PATH="$HOME/.local/bin:$PATH"
    

    Windows (PowerShell):

    npm run playwright-cli:install-browsers
    
  5. Set up environment variables:

    macOS / Linux:

    cp env/.env.example env/.env.dev
    

    Windows (PowerShell):

    Copy-Item env\.env.example env\.env.dev
    

    Edit env/.env.dev with your application's configuration.

  6. Run tests:

    npm test
    

Verify Your Installation

After any setup method, confirm all tools are available:

macOS / Linux:

playwright --version
playwright-cli --version

Windows (PowerShell):

npx playwright --version
playwright-cli --version

Expected output (exact versions vary with your installed packages):

playwright --version      → Version 1.60.0
playwright-cli --version  → 0.1.13

Getting Started: Adapting the Scaffold

This scaffold ships with example files that demonstrate every pattern. Here's how to replace them with your real application code, step by step.

Step 1: Configure Your Environment

Edit env/.env.dev with your application's actual URLs and credentials:

APP_URL=https://your-real-app.com
API_URL=https://your-real-api.com
[email protected]
APP_PASSWORD=your-test-password

Step 2: Update Enums

Open enums/app/app.ts and replace the placeholder values with your app's actual messages, API endpoints, and storage state paths:

export enum Messages {
    LOGIN_SUCCESS = 'Your actual success message',
    LOGIN_ERROR = 'Your actual error message',
    // Add more messages as needed
}

export enum ApiEndpoints {
    LOGIN = '/your/actual/login/endpoint',
    // Add more endpoints as needed
}

Step 3: Create Your First Page Object

Replace pages/app/app.page.ts with a page object for your application's actual login page (or whichever page you're testing first). Use the existing file as a template:

  1. Update the locators to match your app's actual elements
  2. Update the action methods to match your app's actual behavior
  3. Keep the same patterns: getter locators, JSDoc comments, Promise<void> return types

Tip: If using Cursor with AI, ask it to "navigate to [your-url] and create a page object" -- the AI rules will guide it to use playwright-cli by default to explore the page and generate accurate locators.

Step 4: Update Authentication Setup

Edit helpers/app/createStorageState.ts to match your app's actual login flow. The two functions to update:

Step 5: Write Your First Real Test

Replace the example tests in tests/app/functional/ with tests for your application. Follow the pattern in the example files:

import { expect, test } from '../../../fixtures/pom/test-options';

test.describe('Your Feature', () => {
    test(
        'should do something specific',
        { tag: '@smoke' },
        async ({ appPage }) => {
            await test.step('GIVEN precondition', async () => {
                /* ... */
            });
            await test.step('WHEN action is taken', async () => {
                /* ... */
            });
            await test.step('THEN expected result', async () => {
                /* ... */
            });
        }
    );
});

Step 6: Run and Verify

npm test

What to Keep vs. What to Replace

| Keep As-Is | Replace With Your App

agentic-playwright (idavidov13/agentic-playwright)

Searching Database…

这是什么?一个生产级的 Playwright + TypeScript 脚手架,用于端到端和 API 测试,内置 AI 规则(一部“宪法”和 17 项技能),让 Claude Code、Cursor 和 GitHub Copilot 自动编写符合你团队模式的测试。
它是现成的测试框架,还是我在其上构建的脚手架?它是生成到你自己的项目中的脚手架,而不是你导入的库:它提供一套完整可运行的测试框架(页面对象、API fixture、数据工厂、CI),外加你的编程智能体会自动加载的 AI 规则文件。
我怎么在新项目上把它跑起来?在空的项目目录中运行 npm create(或传入文件夹名称),即可脚手架生成框架、安装依赖和浏览器,并在 5 分钟内对一个实时演示应用运行冒烟测试;另外还提供了 Dev Container 和本地安装脚本。
试用之前我需要安装什么?你需要 Node.js v22.x+ 和 npm v10.x+;Dev Container 选项还需要 Docker Desktop 和编辑器的 Dev Containers 扩展。
示例测试对我的应用直接有效吗?无效——示例文件(AppPage、login.spec.ts、NavigationComponent 等)只用于演示模式;你需要用自己应用的页面、测试和数据替换它们。
我能在 Windows 上运行安装脚本吗?本地安装脚本原生支持 macOS 和 Linux;Windows 用户被建议改用 WSL2,或者走 Dev Container 路线。
“宪法”执行钩子实际会拦截什么?一个 Claude Code PreToolUse 钩子(.claude/scripts/enforceconstitution.py)会在文件被写入之前,拦截任何引入可机械检测违规的 Write/Edit 操作,例如 waitForTimeout、XPath 定位器、z.object 模式、在 spec 中导入 @playwright/test,或 JSON 静态数据。
它支持哪些 AI 编程助手?Claude Code、Cursor 和 GitHub Copilot 各自拥有独立成套的规则树(.claude/、.cursor/、.github/instructions/),会根据你正在编辑的文件自动加载。
什么是置信度门控工作流(Confidence-Gated Workflow)?ai-native-workflow 技能会路由所有非平凡的 AI 工作,并要求每个计划都声明置信度分数、理由和未知项;置信度低于 5 时,智能体必须停下来向你索要缺失的输入,而不是自行猜测。
这是微软官方的 Playwright 项目吗?不是,它是一个独立社区在微软开源 Playwright 之上构建的脚手架;README 明确声明其“与微软无关联(Not affiliated with Microsoft)”。
Creator
idavidov13
Size
0.7 MB
Stars
234
Updated
CommitSep 21
Age
2mo
Commits · 90 Days