# ๐ญ Playwright Test Automation Framework
A modular, scalable test automation framework built with **Playwright** and **TypeScript** using the **Page Object Model (POM)** and **Module Pattern** architecture.
> **Created by [Pramod Dutta](https://thetestingacademy.com)** | [The Testing Academy](https://thetestingacademy.com)
---
## ๐ Architecture Documentation
For a comprehensive visual architecture guide, see:
- ๐ **[Architecture Diagram (HTML)](docs/ARCHITECTURE.html)** - Interactive visual documentation
- ๐ **[Quick Reference Guide](docs/QUICK_REFERENCE.md)** - Commands and best practices
- ๐ค **[AI Agents + MCP Tutor Docs](docs/ai-agents/index.mdx)** - Class pack, prompts, and guardrails
- ๐งฉ **[Agent Instruction Templates](.github/instructions/)** - Planner, Generator, Healer repository rules
### Architecture Overview
<p align="center">
<img src="docs/images/arch.png" alt="Playwright Framework Architecture" width="800"/>
</p>
---
## ๐ Key Features
- **Page Object Model (POM)** - Clean separation of test logic and page interactions
- **Module Pattern** - Business logic layer for complex workflows
- **API Testing Layer** - REST API testing with retry support
- **Custom Fixtures** - Pre-authenticated sessions and enhanced page handling
- **Multi-Browser Support** - Chrome, Firefox, Safari, and Mobile Chrome
- **TypeScript** - Full type safety and IntelliSense support
- **Parallel Execution** - Run tests in parallel across browsers
---
## ๐ Project Structure
```
Playwright_Framework/
โโโ src/
โ โโโ api/ # API testing layer
โ โ โโโ AuthApi.ts # Authentication API methods
โ โ โโโ ProductApi.ts # Product API methods
โ โ โโโ OrderApi.ts # Order API methods
โ โ โโโ index.ts # API exports
โ โโโ config/
โ โ โโโ index.ts # Configuration & test data constants
โ โโโ fixtures/
โ โ โโโ auth.fixture.ts # Pre-authenticated session fixtures
โ โ โโโ index.ts # Main fixtures with page objects & modules
โ โโโ modules/ # Business logic layer
โ โ โโโ LoginModule.ts # Login workflows
โ โ โโโ ProductModule.ts # Product workflows
โ โ โโโ CheckoutModule.ts # Checkout workflows
โ โ โโโ index.ts # Module exports
โ โโโ pages/ # Page Object Model layer
โ โ โโโ LoginPage.ts # Login page locators & actions
โ โ โโโ HomePage.ts # Home page locators & actions
โ โ โโโ ProductPage.ts # Product page locators & actions
โ โ โโโ CheckoutPage.ts # Checkout page locators & actions
โ โ โโโ index.ts # Page exports
โ โโโ testdata/
โ โ โโโ users.json # User test data
โ โ โโโ products.json # Product test data
โ โ โโโ types.ts # TypeScript type definitions
โ โโโ tests/
โ โ โโโ login.spec.ts # Login test specifications
โ โ โโโ product.spec.ts # Product test specifications
โ โ โโโ checkout.spec.ts # Checkout test specifications
โ โโโ utils/
โ โโโ Logger.ts # Structured logging utility
โ โโโ WaitHelper.ts # Custom wait conditions
โ โโโ DataGenerator.ts # Random test data generation
โ โโโ ApiHelper.ts # HTTP request helper with retry
โ โโโ index.ts # Utility exports
โโโ playwright.config.ts # Playwright configuration
โโโ tsconfig.json # TypeScript configuration
โโโ package.json # NPM scripts & dependencies
โโโ .env # Environment variables
โโโ .gitignore # Git ignore rules
```
---
## ๐๏ธ Architecture
### Three-Layer Architecture
The framework follows a **3-layer architecture** that promotes separation of concerns:
```
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LAYER 3: TESTS โ
โ (Test Specifications - login.spec.ts, product.spec.ts) โ
โ โข Test scenarios and assertions โ
โ โข Uses Modules for business workflows โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LAYER 2: MODULES โ
โ (Business Logic - LoginModule, ProductModule, etc.) โ
โ โข Complex workflows and business logic โ
โ โข Orchestrates multiple Page actions โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LAYER 1: PAGES โ
โ (Page Objects - LoginPage, ProductPage, etc.) โ
โ โข Locators defined as arrow functions โ
โ โข Basic UI actions (click, fill, navigate) โ
โ โข No business logic โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
```
---
## ๐ Getting Started
### Prerequisites
- Node.js 18+
- npm or yarn
### Installation
```bash
# Install dependencies
npm install
# Install Playwright browsers
npx playwright install
```
### Configuration
Update the `.env` file with your environment settings:
```env
BASE_URL=https://your-app-url.com
TEST_USERNAME=testuser
TEST_PASSWORD=testpass123
API_TIMEOUT=30000
```
---
## ๐ Available Scripts
| Command | Description |
| ----------------------- | ------------------------------ |
| `npm test` | Run all tests in headless mode |
| `npm run test:headed` | Run tests with browser visible |
| `npm run test:ui` | Open Playwright UI mode |
| `npm run test:debug` | Debug tests with inspector |
| `npm run test:chromium` | Run only Chromium tests |
| `npm run test:firefox` | Run only Firefox tests |
| `npm run test:webkit` | Run only WebKit tests |
| `npm run test:mobile` | Run mobile Chrome tests |
| `npm run test:report` | Show HTML test report |
| `npm run build` | Compile TypeScript |
| `npm run clean` | Clean build artifacts |
| `npm run agents:init` | Scaffold Playwright AI agent instruction files |
| `npm run rules:check` | Run framework rule engine on all files |
| `npm run rules:changed` | Run framework rule engine on changed files |
| `npm run rules:staged` | Run framework rule engine on staged files |
---
## ๐งช Test Coverage
| Test File | Test Cases | Description |
| ------------------ | ------------------------------- | ------------------------------- |
| `login.spec.ts` | 11 | Login, logout, validation |
| `product.spec.ts` | 15 | Product details, cart, wishlist |
| `checkout.spec.ts` | 10 | Checkout flow, promo codes |
| **Total** | **36 tests ร 4 browsers = 144** | |
---
## ๐ Flow Diagrams
### Test Execution Flow
```mermaid
flowchart TB
subgraph Tests["Layer 3: Test Specifications"]
T1[login.spec.ts]
T2[product.spec.ts]
T3[checkout.spec.ts]
end
subgraph Modules["Layer 2: Business Modules"]
M1[LoginModule]
M2[ProductModule]
M3[CheckoutModule]
end
subgraph Pages["Layer 1: Page Objects"]
P1[LoginPage]
P2[HomePage]
P3[ProductPage]
P4[CheckoutPage]
end
subgraph Support["Support Layer"]
F[Fixtures]
U[Utilities]
A[API Layer]
C[Config]
end
T1 --> M1
T2 --> M2
T3 --> M3
M1 --> P1
M1 --> P2
M2 --> P3
M2 --> P2
M3 --> P4
M3 --> P3
Tests --> F
Tests --> U
Modules --> A
Modules --> C
```
### Login Flow Example
```mermaid
sequenceDiagram
participant Test as login.spec.ts
participant Module as LoginModule
participant Page as LoginPage
participant Browser as Browser
Test->>Module: doLogin(username, password)
Module->>Page: navigate()
Page->>Browser: goto('/login')
Module->>Page: enterUsername(username)
Page->>Browser: fill('#username', username)
Module->>Page: enterPassword(password)
Page->>Browser: fill('#password', password)
Module->>Page: clickLogin()
Page->>Browser: click('#login-btn')
Module->>Page: waitForNavigation()
Page-->>Module: success
Module-->>Test: logged in
```
### Checkout Flow
```mermaid
flowchart LR
A[Start] --> B[Login]
B --> C[Browse Products]
C --> D[Add to Cart]
D --> E[Go to Checkout]
E --> F[Fill Shipping]
F --> G[Fill Payment]
G --> H{Apply Promo?}
H -->|Yes| I[Enter Promo Code]
I --> J[Place Order]
H -->|No| J
J --> K[Order Confirmation]
K --> L[End]
```
---
## ๐ง Usage Examples
### Using Page Objects
```typescript
import { LoginPage } from "../pages";
const loginPage = new LoginPage(page);
await loginPage.navigate();
await loginPage.enterUsername("user@example.com");
await loginPage.enterPassword("password123");
await loginPage.clickLogin();
```
### Using Modules
```typescript
import { LoginModule } from "../modules";
const loginModule = new LoginModule(page);
await loginModule.doLogin("user@example.com", "password123");
await loginModule.verifyLoggedIn();
```
### Using Fixtures
```typescript
import { test, expect } from "../fixtures";
test("should show dashboard after login", async ({ authenticatedPage }) => {
// Page is already logged in via fixture
await expect(
authenticatedPage.locator('[data-testid="dashboard"]')
).toBeVisible();
});
test("with page objects", async ({ loginPage, homePage }) => {
await loginPage.navigate();
// Use pre-initialized page objects
});
```
### Using API Layer
```typescript
import { AuthApi, ProductApi } from "../api";
const authApi = new AuthApi();
const token = await authApi.login("user@example.com", "password");
const productApi = new ProductApi();
const products = await productApi.getProducts(token);
```
---
## ๐ ๏ธ Utilities
### Logger
```typescript
import { Logger } from "../utils";
const logger = new Logger("TestName");
logger.info("Starting test");
logger.debug("Debug information");
logger.error("Error occurred", error);
```
### WaitHelper
```typescript
import { WaitHelper } from "../utils";
const waitHelper = new WaitHelper(page);
await waitHelper.waitForCondition(async () => {
return await page.locator(".loading").isHidden();
});
await waitHelper.retry(async () => await fetchData(), 3);
```
### DataGenerator
```typescript
import { DataGenerator } from "../utils";
const email = DataGenerator.randomEmail(); // user_abc123@test.com
const phone = DataGenerator.randomPhoneNumber(); // (555) 123-4567
const uuid = DataGenerator.uuid(); // 550e8400-e29b-41d4-a716-446655440000
```
---
## ๐ Writing New Tests
1. **Create Page Object** (if new page):
```typescript
// src/pages/NewPage.ts
export class NewPage {
constructor(private page: Page) {}
// Locators as arrow functions
readonly submitButton = () => this.page.locator("#submit");
// Actions
async clickSubmit() {
await this.submitButton().click();
}
}
```
2. **Create Module** (for business logic):
```typescript
// src/modules/NewModule.ts
export class NewModule {
private newPage: NewPage;
constructor(page: Page) {
this.newPage = new NewPage(page);
}
async completeWorkflow() {
// Orchestrate multiple page actions
}
}
```
3. **Write Test**:
```typescript
// src/tests/new.spec.ts
import { test, expect } from "../fixtures";
import { NewModule } from "../modules";
test("should complete workflow", async ({ page }) => {
const module = new NewModule(page);
await module.completeWorkflow();
// Assertions
});
```
---
## ๐ Custom TTA Reporter
This framework includes a **Custom TTA Reporter** - a beautiful, modern HTML reporter with real-time test execution updates.
### Features
| Feature | Description |
|---------|-------------|
| ๐จ **Modern UI** | Green-themed design with Google Fonts (Inter, JetBrains Mono) |
| ๐ **Stats Dashboard** | 6 metric cards showing Total, Passed, Failed, Skipped, Pass Rate, Duration |
| ๐ **Console Logs per Step** | Each `console.log()` in `test.step()` is captured and displayed |
| ๐ฌ **Screenshots & Videos** | Auto-captured on failure with inline previews |
| ๐ **Trace Viewer** | Direct links to Playwright trace files |
| ๐ **Filters** | Filter by Priority (P0, P1, P2) and Status (Passed/Failed/Skipped) |
| โฑ๏ธ **Real-time Updates** | Live console output during test execution |
### Report Screenshot
<p align="center">
<img src="docs/images/report.png" alt="TTA Custom Reporter Screenshot" width="800"/>
</p>
### Usage
The reporter is automatically configured in `playwright.config.ts`:
```typescript
reporter: [
['./src/utils/CustomTTAReporter.ts'],
['html', { open: 'never' }],
['json', { outputFile: 'test-results/results.json' }],
['list'],
],
```
### Console Log Capture
Capture console logs in your test steps:
```typescript
test('example test', async ({ page }) => {
await test.step('Verify page title', async () => {
const title = await page.title();
console.log(`Page Title: ${title}`); // โ Appears in step's console output
expect(title).toBeTruthy();
});
});
```
Reports are generated in `tta-report/` directory with timestamped filenames.
---
## ๐ Reports
After running tests, view the HTML report:
```bash
npm run test:report
```
Reports are generated in:
- `tta-report/` - Custom TTA HTML reports (recommended)
- `playwright-report/` - Default Playwright HTML report
- `test-results/` - JSON results and screenshots
---
## ๐ณ Docker Support
Run tests in containerized environments with parallel sharding:
### Using Dockerfile
```bash
# Build the image
docker build -t playwright-framework .
# Run all tests
docker run --rm playwright-framework
# Run smoke tests
docker run --rm playwright-framework npx playwright test --grep @Smoke
# Run with sharding (shard 1 of 4)
docker run --rm playwright-framework npx playwright test --shard=1/4
# Mount results directory
docker run --rm -v $(pwd)/results:/app/test-results playwright-framework
```
### Using Docker Compose (Parallel Shards)
```bash
# Run all 4 shards in parallel
docker-compose up
# Run only smoke tests
docker-compose up smoke
# Run single shard
docker-compose up shard-1
# Stop and clean up
docker-compose down
```
---
## ๐ CI/CD Integration
### GitHub Actions
The framework includes pre-configured GitHub Actions workflows:
| Workflow | Trigger | Description |
|----------|---------|-------------|
| `playwright.yml` | Push/PR to main, develop | Full test suite with 4 parallel shards |
| `smoke-tests.yml` | Pull requests | Quick smoke tests (@P0, @Smoke) |
**Features:**
- โ
Parallel test execution with sharding
- โ
Automatic artifact upload (reports, screenshots)
- โ
GitHub Summary with test results
- โ
Manual trigger with custom test tags
### Jenkins Pipeline
```bash
# The Jenkinsfile supports:
- Parameterized builds (test type, browser, shard count)
- Docker-based execution
- HTML report publishing
- Slack notifications (optional)
```
---
## ๐ง Code Quality Tools
### ESLint + Prettier
```bash
# Run linting
npm run lint
# Fix linting issues
npm run lint:fix
# Format code
npm run format
# Check formatting
npm run format:check
```
### Configuration Files
| File | Purpose |
|------|---------|
| `.eslintrc.json` | ESLint rules (TypeScript + Playwright) |
| `.prettierrc` | Code formatting rules |
| `.editorconfig` | Editor settings consistency |
### Husky + Commitlint
Pre-commit hooks ensure code quality:
```bash
# Pre-commit hook runs:
- ESLint on staged files
- TypeScript type checking
- Framework rule engine on staged files
# Commit message validation:
# Format: type(scope): description
# Example: feat(login): add remember me functionality
```
**Valid commit types:**
`feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`
---
## ๐ค AI Assistant Support
This framework is optimized for AI-assisted development:
| Tool | Configuration File | Description |
|------|-------------------|-------------|
| **Augment Code** | `.augment/rules/` | Framework rules + code standards |
| **GitHub Copilot** | `.github/copilot-instructions.md` | Copilot-specific instructions |
| **Cursor AI** | `.cursorrules` | Cursor editor rules |
| **Windsurf AI** | `.windsurfrules` | Windsurf editor rules |
AI assistants are trained to:
- Follow 3-layer architecture (Pages โ Modules โ Tests)
- Use arrow functions for locators
- Include test.step() for reporting
- Apply proper test tags (@P0, @Smoke, etc.)
---
## ๐ค Contributing
1. Follow the existing architecture patterns
2. Keep Page Objects focused on locators and basic actions
3. Put business logic in Modules
4. Write descriptive test names
5. Use TypeScript types consistently
6. Use conventional commit messages
---
## ๐ Project Files Structure
```
Playwright_Framework/
โโโ .github/
โ โโโ workflows/
โ โ โโโ playwright.yml # Main CI workflow
โ โ โโโ smoke-tests.yml # PR smoke tests
โ โโโ copilot-instructions.md # GitHub Copilot rules
โโโ .augment/rules/
โ โโโ framework-rules.md # Page Object & Module patterns
โ โโโ code-standards.md # Coding standards
โโโ .husky/
โ โโโ pre-commit # Pre-commit hooks
โ โโโ commit-msg # Commit message validation
โโโ docs/
โ โโโ images/
โ โ โโโ arch.png # Architecture diagram
โ โ โโโ report.png # Reporter screenshot
โ โโโ ARCHITECTURE.html # Visual architecture
โ โโโ QUICK_REFERENCE.md # Commands & best practices
โ โโโ ai-agents/ # AI agents + MCP tutorial docs
โโโ rules/
โ โโโ framework-rule-engine.json # Architecture and placement rules
โโโ scripts/
โ โโโ rule-engine.js # Rule engine validator script
โโโ skills/
โ โโโ playwright-ai-mcp-tutor/ # Reusable tutor skill pack
โโโ Dockerfile # Docker image config
โโโ docker-compose.yml # Docker Compose with sharding
โโโ Jenkinsfile # Jenkins pipeline
โโโ .eslintrc.json # ESLint configuration
โโโ .prettierrc # Prettier configuration
โโโ .editorconfig # Editor configuration
โโโ .cursorrules # Cursor AI rules
โโโ .windsurfrules # Windsurf AI rules
โโโ commitlint.config.js # Commit message rules
โโโ playwright.config.ts # Playwright configuration
```
---
## ๐งญ Why We Added Rule Engine and AI/MCP Controls
These additions were made to keep AI-assisted automation deterministic, reviewable, and framework-compliant.
- **Rule Engine (`rules/framework-rule-engine.json` + `scripts/rule-engine.js`)**
- Enforces file placement (`Page` -> `src/pages`, `Module/Modal` -> `src/modules`, `spec` -> `src/tests`, utilities -> `src/utils`)
- Enforces architecture patterns (no direct locator usage in modules, tags and `test.step()` in specs)
- Reduces random code generation and framework drift before code reaches PR review
- **AI Agent Instructions (`.github/instructions/`)**
- Defines clear responsibilities for `Planner`, `Generator`, and `Healer`
- Keeps generation constrained to repository standards and naming rules
- Encourages minimal, evidence-based healing instead of broad rewrites
- **MCP + Tutor Docs (`docs/ai-agents/` and `mint.json`)**
- Provides a simple training path for teaching AI-assisted Playwright workflows
- Shows prompt templates and validation gates to reduce hallucination risk
- Helps new contributors follow the same process from planning to healing
- **Skill Pack (`skills/playwright-ai-mcp-tutor/`)**
- Reusable instruction bundle for repeating the same teaching workflow
- Standardizes prompts, guardrails, and expected outputs across batches
---
## ๐ License
ISC
---
## ๐จโ๐ป Author
**Pramod Dutta**
- Website: [thetestingacademy.com](https://thetestingacademy.com)
- GitHub: [@PramodDutta](https://github.com/PramodDutta)
---
<p align="center">
Built with โค๏ธ by <a href="https://thetestingacademy.com">The Testing Academy</a>
</p>