### Create New Playwright Project with CLI Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Demonstrates commands for creating a new Playwright project using the CLI. Supports interactive setup, non-interactive setup with defaults, skipping dependency installation, and forcing creation into an existing directory. ```bash # Interactive setup with template selection npx @netanelh2/create-playwright-project my-test-project # Non-interactive with all defaults npx @netanelh2/create-playwright-project my-tests --yes # Without dependency installation npx @netanelh2/create-playwright-project my-tests --no-install # Force into existing directory npx @netanelh2/create-playwright-project existing-project --force ``` -------------------------------- ### Project Setup and Build Scripts Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/README.md Provides essential bash commands for cloning the repository, installing dependencies, building the project, and running various development tasks like testing, linting, and type checking. ```bash git clone https://github.com/NetanelH2/playwright-framework-suite.git cd playwright-framework-suite npm install npm run build ``` ```bash npm run build # Build both packages (ES modules) npm run build:framework # Build framework package only npm run build:cli # Build CLI package only npm test # Run all tests npm run check # Run Biome linting and formatting npm run type-check # TypeScript 5.x compilation check npm run clean # Clean build artifacts ``` -------------------------------- ### Install Project Dependencies with Playwright Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/create-playwright-project/templates/base/README.md Installs project dependencies using npm and downloads the necessary Playwright browser binaries. ```bash npm install npx playwright install ``` -------------------------------- ### Create New Playwright Project CLI Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Scaffolds a new Playwright project with pre-configured settings, example page objects, tests, TypeScript, Biome, and environment setup. This command-line interface tool simplifies project initialization. ```bash npx @netanelh2/create-playwright-project my-new-project ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/create-playwright-project/templates/base/README.md Copies an example environment file and instructs the user to edit it with application-specific settings like the base URL. ```bash cp .env.example .env # Edit .env with your application URL and settings ``` -------------------------------- ### Environment Variable Configuration Example Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/create-playwright-project/templates/base/README.md Shows an example of how to configure environment variables for the Playwright project, primarily setting the base URL for the application under test. ```env BASE_URL=https://your-app.com # Add other environment variables as needed ``` -------------------------------- ### GitHub Actions Workflow Setup Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Provides the command-line instruction to automatically set up GitHub Actions workflows for a project using the '@netanelh2/create-workflows-package' utility. The `--yes` flag suggests accepting default configurations. ```bash # Add workflows to existing project npx @netanelh2/create-workflows-package --yes ``` -------------------------------- ### Install Core Playwright Framework Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Installs the core Playwright framework, the test runner, and TypeScript as development dependencies. Ensures the project is set up to use ES modules and has the required Node.js and npm versions. ```bash npm install --save-dev @netanelh2/playwright-framework @playwright/test typescript ``` -------------------------------- ### Project Structure Overview Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/create-playwright-project/templates/base/README.md Illustrates the typical directory structure of the Playwright TypeScript project, categorizing files by their role in the testing framework. ```text src/ ├── tests/ # Test specifications ├── pages/ # Page Object Models ├── locators/ # Centralized locators ├── fixtures/ # Test fixtures and setup ├── helpers/ # Utility functions └── types/ # TypeScript type definitions ``` -------------------------------- ### Write a Playwright Test Case in TypeScript Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/create-playwright-project/templates/base/README.md Demonstrates a basic Playwright test case written in TypeScript, utilizing fixtures and page object methods to navigate and validate a page. ```typescript import {test} from '../fixtures/testSetup' test.describe('Example Feature @sanity', () => { test('should perform basic action', async ({mainPage}) => { await mainPage.navigateTo() await mainPage.validatePageLoaded() }) }) ``` -------------------------------- ### Run Playwright Tests with npm Scripts Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/create-playwright-project/templates/base/README.md Provides various npm scripts to execute Playwright tests, including running all tests, with UI, in debug mode, or specific tagged suites. ```bash npm test # All tests npm run test:headed # With browser UI npm run test:debug # Debug mode npm run test:chrome # Run tests in Chromium only npm run test:sanity # Run tests tagged with @sanity npm run test:regression # Run tests tagged with @regression npm run test:sanity:chrome npm run test:regression:chrome npm run report npm run codegen ``` -------------------------------- ### Add GitHub Actions Workflows with CLI Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Shows commands for adding GitHub Actions workflows to an existing project. Options include interactive workflow selection, including all workflows non-interactively, and setting up workflows without installing dependencies. ```bash # Interactive workflow selection npx @netanelh2/create-workflows-package # Include all workflows without prompts npx @netanelh2/create-workflows-package --yes # Setup without installing dependencies npx @netanelh2/create-workflows-package --no-install ``` -------------------------------- ### Git Hooks Commands (npm/yarn) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/create-workflows-package/README.md These bash commands manage Git hooks using npm or yarn. 'npm run prepare' is used to set up Husky, a tool for managing Git hooks, and should typically be run once. These commands automate pre-commit checks and other Git-related processes. ```bash # Git Hooks npm run prepare # Setup Husky (run once) ``` -------------------------------- ### Create Page Objects with BasePage Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Provides an example of creating a page object (LoginPage) that extends the BasePage class from the Playwright Framework. It demonstrates navigation, user actions like login, and validation methods. ```typescript import { BasePage, type Page } from '@netanelh2/playwright-framework' import { test } from '../fixtures/testSetup' import { LOGIN_PAGE_LOCATORS as L } from '../locators/login/Login_Page' export class LoginPage extends BasePage { constructor(page: Page) { super(page) } async navigateTo(): Promise { await this.gotoURL('/login') } async login(username: string, password: string): Promise { await test.step('User login flow', async () => { const usernameLocator = this.extractLocator(L.usernameField) const passwordLocator = this.extractLocator(L.passwordField) await usernameLocator.fill(username) await passwordLocator.fill(password) await this.clickOnElement(L.submitButton) }) } async validateLoaded(): Promise { await this.validateVisibility(L.usernameField) await this.validateVisibility(L.submitButton) } async validateLoginError(): Promise { await this.validateVisibility(L.errorMessage) await this.validateText(L.errorMessage, 'Invalid credentials') } } ``` -------------------------------- ### Write Tests with Custom Fixtures (TypeScript) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/README.md Illustrates how to write Playwright tests using custom fixtures, such as `loginPage` and `dashboardPage`. This example demonstrates a typical authentication test flow, navigating to a page, logging in, and validating successful login. ```typescript import {test} from '../fixtures/testSetup' import {STANDARD_USER} from '../data/users' test.describe('Authentication @sanity', () => { test('should login successfully', async ({loginPage, dashboardPage}) => { await loginPage.navigateTo() await loginPage.validateLoaded() await loginPage.login(STANDARD_USER.username, STANDARD_USER.password) await dashboardPage.validateUserLoggedIn() }) }) ``` -------------------------------- ### Run Playwright Tests with Fixture Injection Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/AGENTS.md This example shows how to import a custom test fixture, which injects page objects like 'mainPage', and use it within a test describe block to load and validate the main page. It also demonstrates tag-based filtering for test runs. ```typescript // src/tests/main.spec.ts (fixture-based injection) import { test } from "../fixtures/testSetup"; test.describe("Main Page @sanity", () => { test("loads and shows content", async ({ mainPage }) => { await mainPage.openMainPage(); await mainPage.validateContactOnMainPage(); }); }); ``` -------------------------------- ### Scaffold New Playwright Project with CLI Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/create-playwright-project/README.md Initiates the creation of a new Playwright TypeScript project. Users can specify a project name or use interactive mode. Options include skipping dependency installation or git initialization, and forcing scaffolding into existing directories. ```bash npx @netanelh2/create-playwright-project my-project-name npm install -g @netanelh2/create-playwright-project create-playwright-project my-project-name npx @netanelh2/create-playwright-project npx @netanelh2/create-playwright-project my-awesome-tests npx @netanelh2/create-playwright-project my-project --yes npx @netanelh2/create-playwright-project my-tests --yes npx @netanelh2/create-playwright-project my-tests --no-install npx @netanelh2/create-playwright-project my-tests --no-git npx @netanelh2/create-playwright-project existing-folder --force npx @netanelh2/create-playwright-project existing-project --force ``` -------------------------------- ### Playwright Configuration with Framework Utilities Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Provides an example of a `playwright.config.ts` file that integrates custom configurations with utilities from '@netanelh2/playwright-framework', such as `getEnvCredentials` for setting `baseURL`. It includes standard Playwright settings for test directories, timeouts, reporters, parallel execution, and project definitions. ```typescript // playwright.config.ts import { defineConfig, devices } from '@playwright/test' import { getEnvCredentials } from '@netanelh2/playwright-framework' export default defineConfig({ testDir: './src/tests', timeout: 60 * 1000, fullyParallel: true, forbidOnly: !!process.env.CI, retries: process.env.CI ? 2 : 0, workers: process.env.CI ? 4 : undefined, reporter: [ ['html', { open: 'never' }], ['list'], ['json', { outputFile: 'test-results.json' }], ], use: { baseURL: getEnvCredentials('BASE_URL'), trace: 'on-first-retry', screenshot: { mode: 'only-on-failure', fullPage: true }, video: 'retain-on-failure', actionTimeout: 15000, navigationTimeout: 30000, }, projects: [ { name: 'chromium', use: { ...devices['Desktop Chrome'] }, }, { name: 'firefox', use: { ...devices['Desktop Firefox'] }, }, { name: 'webkit', use: { ...devices['Desktop Safari'] }, }, ], }) ``` -------------------------------- ### Using Environment Variables for Configuration (TypeScript) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Explains how to use environment variables for managing configuration settings like base URLs and API endpoints. It shows a `.env` file example and how to access these variables using `getEnvCredentials` from the framework. ```typescript // .env BASE_URL=https://staging.example.com API_ENDPOINT=https://api.example.com DEFAULT_TIMEOUT=30000 // Usage import { getEnvCredentials } from '@netanelh2/playwright-framework'; export const BASE_URL = getEnvCredentials('BASE_URL'); export const API_ENDPOINT = getEnvCredentials('API_ENDPOINT'); ``` -------------------------------- ### Configure GitHub Actions for Sanity Tests (YAML) Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt This YAML configuration sets up a GitHub Actions workflow to run sanity tests. It checks out the code, sets up Node.js, installs dependencies, runs the test script, and uploads test reports as an artifact. It requires a `BASE_URL` secret for test execution. ```yaml name: Sanity Tests on: pull_request: branches: [main, develop] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '18' - run: npm ci - run: npm run test:sanity env: BASE_URL: ${{ secrets.BASE_URL }} - uses: actions/upload-artifact@v4 if: always() with: name: playwright-report path: playwright-report/ ``` -------------------------------- ### Playwright Test Scripts in package.json Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/create-workflows-package/README.md This JSON object defines various scripts within the 'package.json' file for running Playwright tests. It includes commands for standard tests, sanity and regression checks, specific browser testing, headed mode, debugging, and generating test reports. These scripts automate common testing workflows. ```json { "scripts": { "test": "playwright test", "test:sanity": "playwright test --grep '@sanity'", "test:regression": "playwright test --grep '@regression'", "test:chrome": "playwright test --project=chromium", "test:headed": "playwright test --headed", "test:debug": "playwright test --debug", "report": "playwright show-report" } } ``` -------------------------------- ### Write Type-Safe Playwright Tests Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Provides examples of type-safe End-to-End tests using the custom fixtures and page objects defined earlier. It covers scenarios for successful login, invalid credentials, and admin access, demonstrating the framework's structure. ```typescript // src/tests/login.spec.ts import {STANDARD_USER, ADMIN_USER} from '../data/users' import {test} from '../fixtures/testSetup' test.describe('Login Flow @sanity', () => { test('should login successfully with standard user', async ({ loginPage, dashboardPage, }) => { await loginPage.navigateTo() await loginPage.validateLoaded() await loginPage.login(STANDARD_USER.username, STANDARD_USER.password) await dashboardPage.validateUserLoggedIn(STANDARD_USER.username) }) test('should display error for invalid credentials', async ({loginPage}) => { await loginPage.navigateTo() await loginPage.login('invalid_user', 'wrong_password') await loginPage.validateLoginError() }) }) test.describe('Admin Login @regression', () => { test('should allow admin access', async ({loginPage, dashboardPage}) => { await loginPage.navigateTo() await loginPage.login(ADMIN_USER.username, ADMIN_USER.password) await dashboardPage.validateAdminAccess() }) }) ``` -------------------------------- ### Define Locators and Page Object for Login Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/AGENTS.md This snippet demonstrates how to define locators for the login page using UPPER_SNAKE_CASE with the _LOCATORS suffix and create a LoginPage class extending BasePage. It includes methods for navigation and validation. ```typescript // src/locators/content-pages/Login_Page.ts export const LOGIN_PAGE_LOCATORS = { form: { parent: "#login", role: "textbox", name: "Username" }, submit: { role: "button", name: "Submit" }, } as const; // src/pages/LoginPage.ts import { BasePage } from "../core/BasePage"; import { BASE_URL } from "../data/urls"; import { LOGIN_PAGE_LOCATORS as L } from "../locators/content-pages/Login_Page"; export class LoginPage extends BasePage { async navigateTo(): Promise { await this.gotoURL(BASE_URL + "/login"); } async validateLoaded(): Promise { await this.validateVisibility(L.form); } } ``` -------------------------------- ### Locator Strategies: Role-Based vs. CSS vs. Avoid (TypeScript) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Highlights the preferred method for defining locators in Playwright, emphasizing the use of role-based locators for accessibility and maintainability. It also provides examples of acceptable CSS selectors and demonstrates fragile selectors to avoid. ```typescript // ✅ Preferred: Role-based (accessibility-friendly) const loginButton = {role: 'button', name: 'Login'} // ⚠️ Acceptable: CSS when role-based isn't suitable const errorMessage = '.error-message' // ❌ Avoid: Fragile selectors const button = 'div > div > button:nth-child(3)' ``` -------------------------------- ### Writing Playwright Tests with Custom Fixtures and Data in TypeScript Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Demonstrates how to write Playwright end-to-end tests using custom fixtures and predefined test data. It defines user credentials and then uses the custom `test` object (with fixtures) to perform login scenarios and validate user states. This approach simplifies test writing and promotes data-driven testing. It depends on the custom fixture setup and page object methods. ```typescript // src/data/users.ts import type { UserCredentials } from '../types/userTypes' export const STANDARD_USER: UserCredentials = { username: 'standard_user', password: 'secret_sauce', role: 'user', } export const ADMIN_USER: UserCredentials = { username: 'admin', password: 'admin123', role: 'admin', } // src/tests/login.spec.ts import { STANDARD_USER, ADMIN_USER } from '../data/users' import { test } from '../fixtures/testSetup' test.describe('Login Flow @sanity', () => { test('should login successfully with standard user', async ({ loginPage, dashboardPage }) => { await loginPage.navigateTo() await loginPage.validateLoaded() await loginPage.login(STANDARD_USER.username, STANDARD_USER.password) await dashboardPage.validateUserLoggedIn(STANDARD_USER.username) }) test('should display error for invalid credentials', async ({ loginPage }) => { await loginPage.navigateTo() await loginPage.login('invalid_user', 'wrong_password') await loginPage.validateLoginError() }) }) test.describe('Admin Login @regression', () => { test('should allow admin access', async ({ loginPage, dashboardPage }) => { await loginPage.navigateTo() await loginPage.login(ADMIN_USER.username, ADMIN_USER.password) await dashboardPage.validateAdminAccess() }) }) ``` -------------------------------- ### Implementing Page Validation Methods (TypeScript) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Provides an example of creating validation methods within a page object to assert the state of a page. This includes validating element visibility and checking the current URL, promoting robust UI testing. ```typescript export class ProductPage extends BasePage { async validateLoaded(): Promise { await this.validateVisibility(PRODUCT_PAGE_LOCATORS.productGrid) await this.validateVisibility(PRODUCT_PAGE_LOCATORS.filterSection) await this.validateURL('/products') } } ``` -------------------------------- ### Combined Locator Definition in TypeScript Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Presents a comprehensive example of defining page locators using a combination of role-based and string-based strategies within a TypeScript Record. This approach centralizes locator definitions, promoting consistency and maintainability, with a preference for role-based locators for better accessibility. ```typescript import type {StringOrRoleLocatorType} from '@netanelh2/playwright-framework' export const PAGE_LOCATORS = { // Role-based (preferred for accessibility) submitButton: {role: 'button', name: 'Submit'}, emailInput: {role: 'textbox', name: 'Email'}, // CSS selectors (when role-based isn't suitable) errorMessage: '.error-message', loadingSpinner: '#loading', // With parent context formSubmit: { parent: '.checkout-form', role: 'button', name: 'Complete Order', }, } as const satisfies Record ``` -------------------------------- ### Custom Page with LocatorUtils for Element Handling Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Illustrates extending the LocatorUtils class to create custom page interactions. This snippet shows how to efficiently extract and interact with elements using flexible locator strategies, such as getting element text and checking visibility. It leverages the framework's locator handling capabilities. ```typescript import { LocatorUtils, type Page, type StringOrRoleLocatorType, } from '@netanelh2/playwright-framework' export class CustomPage extends LocatorUtils { constructor(page: Page) { super(page) } async getElementText(locator: StringOrRoleLocatorType): Promise { const element = this.extractLocator(locator) return (await element.textContent()) ?? '' } async isElementVisible(locator: StringOrRoleLocatorType): Promise { const element = this.extractLocator(locator) return await element.isVisible() } } ``` -------------------------------- ### Code Quality Commands (npm/yarn) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/create-workflows-package/README.md These bash commands utilize npm or yarn to execute code quality checks. 'npm run check' initiates both Biome linting/formatting and TypeScript type checking. 'npm run type-check' specifically runs TypeScript's type checking without making any modifications. ```bash # Code Quality npm run check # Run Biome linting, formatting, and type checking npm run type-check # Run TypeScript type checking only ``` -------------------------------- ### Creating Custom Playwright Test Fixtures in TypeScript Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Defines custom test fixtures for Playwright tests to streamline setup and access to page objects. It uses the `baseTest.extend` method to create fixtures like `loginPage` and `dashboardPage`, which are instances of corresponding page classes. This improves test maintainability by centralizing page object instantiation. It depends on page object classes and Playwright's test runner. ```typescript // src/types/fixtureTypes.ts import type { LoginPage } from '../pages/LoginPage' import type { DashboardPage } from '../pages/DashboardPage' export interface PageFixtures { loginPage: LoginPage dashboardPage: DashboardPage } // src/fixtures/testSetup.ts import { test as baseTest } from '@netanelh2/playwright-framework' import { LoginPage } from '../pages/LoginPage' import { DashboardPage } from '../pages/DashboardPage' import type { PageFixtures } from '../types/fixtureTypes' export const test = baseTest.extend({ loginPage: async ({ page }, use) => { const loginPage = new LoginPage(page) await use(loginPage) }, dashboardPage: async ({ page }, use) => { const dashboardPage = new DashboardPage(page) await use(dashboardPage) }, }) export { expect } from '@playwright/test' ``` -------------------------------- ### Code Quality and Type Checking Scripts in package.json Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/create-workflows-package/README.md This JSON object contains scripts for maintaining code quality and performing type checking using Biome and TypeScript. The 'check' script runs Biome's linter and formatter along with TypeScript's type checking, while 'type-check' focuses solely on TypeScript's type validation. These scripts are crucial for ensuring code consistency and correctness. ```json { "scripts": { "check": "npx @biomejs/biome check --write && npx tsc --noEmit", "type-check": "tsc --noEmit", "pre-commit": "lint-staged", "prepare": "husky" } } ``` -------------------------------- ### Custom Locator Interactions with TypeScript Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Extends Playwright's LocatorUtils to provide custom methods for interacting with elements. It abstracts common operations like getting text content, checking visibility, counting elements, and performing waited clicks. This enhances reusability and readability of test code. It depends on the Page and StringOrRoleLocatorType from the framework. ```typescript import { LocatorUtils, type Page, type StringOrRoleLocatorType } from '@netanelh2/playwright-framework' export class CustomPage extends LocatorUtils { constructor(page: Page) { super(page) } async getElementText(locator: StringOrRoleLocatorType): Promise { const element = this.extractLocator(locator) return (await element.textContent()) ?? '' } async isElementVisible(locator: StringOrRoleLocatorType): Promise { const element = this.extractLocator(locator) return await element.isVisible() } async getElementCount(locator: StringOrRoleLocatorType): Promise { const element = this.extractLocator(locator) return await element.count() } async waitAndClick(locator: StringOrRoleLocatorType): Promise { const element = this.extractLocator(locator) await element.waitFor({ state: 'visible', timeout: 10000 }) await element.click() } } ``` -------------------------------- ### Quick Contribution Steps (Bash) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/README.md Provides a concise list of bash commands for contributing to the project. These steps cover forking the repository, creating a feature branch, making changes, adding a changeset, running quality checks, committing, and pushing the changes. ```bash 1. **Fork the repository** 2. **Create a feature branch**: `git checkout -b feature/my-feature` 3. **Make your changes** and add a changeset: `npm run changeset` 4. **Run quality checks**: `npm run check` 5. **Commit**: `git commit -m "feat: add my feature"` 6. **Push**: `git push origin feature/my-feature` 7. **Submit a Pull Request** using the provided template ``` -------------------------------- ### Product Page Interactions with BasePage Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Demonstrates how to use BasePage methods for interacting with elements on a product page, such as adding items to the cart, filtering by category, searching for products, and navigating to checkout. Assumes the existence of BasePage and Page types from '@netanelh2/playwright-framework'. ```typescript import { BasePage, type Page } from '@netanelh2/playwright-framework' import { PRODUCT_LOCATORS as L } from '../locators/products/Product_Page' export class ProductPage extends BasePage { constructor(page: Page) { super(page) } async addProductToCart(productName: string): Promise { // Click on element await this.clickOnElement({ role: 'button', name: `Add ${productName} to cart` }) } async filterByCategory(category: string): Promise { // Hover and click await this.hoverOnElement(L.categoryDropdown) await this.clickOnElement({ role: 'option', name: category }) } async searchProduct(searchTerm: string): Promise { // Fill input field await this.fillInput(L.searchInput, searchTerm) await this.clickOnElement(L.searchButton) } async navigateToCheckout(): Promise { // Navigation await this.gotoURL('/checkout') await this.validateURL('/checkout') } } ``` -------------------------------- ### Playwright Configuration (TypeScript) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Provides a recommended Playwright configuration file (`playwright.config.ts`) for setting up test directories, timeouts, parallel execution, reporters, and project-specific browser configurations. It utilizes environment variables for dynamic settings like `baseURL`. ```typescript // playwright.config.ts import {defineConfig, devices} from '@playwright/test' export default defineConfig({ testDir: './src/tests', timeout: 60 * 1000, fullyParallel: true, forbidOnly: !!process.env.CI, retries: process.env.CI ? 2 : 0, workers: process.env.CI ? 4 : undefined, reporter: [['html', {open: 'never'}], ['list']], use: { baseURL: process.env.BASE_URL || 'http://localhost:3000', trace: 'on-first-retry', screenshot: {mode: 'only-on-failure', fullPage: true}, video: 'retain-on-failure', }, projects: [ { name: 'chromium', use: {...devices['Desktop Chrome']}, }, { name: 'firefox', use: {...devices['Desktop Firefox']}, }, { name: 'webkit', use: {...devices['Desktop Safari']}, }, ], }) ``` -------------------------------- ### Main Framework Imports (TypeScript) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Lists the primary exports available from the main `@netanelh2/playwright-framework` package, including core classes, utilities, and type definitions for general use. ```typescript // Main framework exports (classes, utilities, types) import { BasePage, LocatorUtils, getEnvCredentials, findItemByProperty, } from '@netanelh2/playwright-framework' ``` -------------------------------- ### NPM Scripts for Test Execution and Quality Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Lists common npm scripts used for managing and running tests within a Playwright project. Includes commands for standard test execution, headed mode, specific browser runs, tag-based filtering (sanity, regression), debugging, generating reports, and code quality checks using Biome and TypeScript. ```bash # Testing scripts npm test # Run all tests npm run test:headed # Run with browser UI visible npm run test:chrome # Run in Chrome only npm run test:sanity # Run @sanity tagged tests npm run test:regression # Run @regression tagged tests npm run test:sanity:chrome # Run @sanity tests in Chrome npm run test:debug # Open Playwright Inspector npm run report # View HTML test report npm run codegen # Launch code generator # Code quality scripts npm run check # Biome lint + format + TypeScript check npm run type-check # TypeScript validation only npm run pre-commit # Pre-commit hooks (lint-staged) ``` -------------------------------- ### Using test.step() for Readable Test Reports (TypeScript) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Demonstrates how to use `test.step()` to logically group actions within Playwright tests. This enhances the readability of test reports by breaking down complex steps into named, understandable sections. ```typescript async login(username: string, password: string): Promise { await test.step('Fill login credentials', async () => { await this.fillInput(L.usernameField, username); await this.fillInput(L.passwordField, password); }); await test.step('Submit login form', async () => { await this.clickOnElement(L.submitButton); }); } ``` -------------------------------- ### Page Object with BasePage and Navigation/Validation Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Demonstrates a Page Object Model implementation using the BasePage class. It includes navigation methods like navigateTo and validation methods like validateLoaded and validateUserLoggedIn. This pattern enhances test maintainability and readability. ```typescript import { BasePage, type Page, type StringOrRoleLocatorType, } from '@netanelh2/playwright-framework' export class DashboardPage extends BasePage { private readonly LOCATORS = { header: {role: 'banner'}, userMenu: {role: 'button', name: 'User Menu'}, welcomeMessage: '.welcome-message', } as const satisfies Record constructor(page: Page) { super(page) } // Navigation async navigateTo(): Promise { await this.gotoURL('/dashboard') } // Validation async validateLoaded(): Promise { await this.validateVisibility(this.LOCATORS.header) await this.validateURL('/dashboard') } async validateUserLoggedIn(username: string): Promise { await this.validateText( this.LOCATORS.welcomeMessage, `Welcome, ${username}`, ) } // Interactions async openUserMenu(): Promise { await this.clickOnElement(this.LOCATORS.userMenu) } } ``` -------------------------------- ### Create Type-Safe Page Objects with Playwright Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Illustrates the creation of a `LoginPage` class that extends `BasePage` from the Playwright framework. It utilizes type-safe locators and includes methods for navigation, user login, and validation of UI elements and error messages. ```typescript import {BasePage, type Page} from '@netanelh2/playwright-framework' import {test} from '../fixtures/testSetup' import {LOGIN_PAGE_LOCATORS as L} from '../locators/login/Login_Page' export class LoginPage extends BasePage { constructor(page: Page) { super(page) } async navigateTo(): Promise { await this.gotoURL('/login') } async login(username: string, password: string): Promise { await test.step('User login flow', async () => { const usernameLocator = this.extractLocator(L.usernameField) const passwordLocator = this.extractLocator(L.passwordField) await usernameLocator.fill(username) await passwordLocator.fill(password) await this.clickOnElement(L.submitButton) }) } async validateLoaded(): Promise { await this.validateVisibility(L.usernameField) await this.validateVisibility(L.submitButton) } async validateLoginError(): Promise { await this.validateVisibility(L.errorMessage) } } ``` -------------------------------- ### Environment Variables Utility for Credentials Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Shows how to use the `getEnvCredentials` utility from '@netanelh2/playwright-framework' to load environment variables for configuration, such as base URLs, API keys, and timeouts. It demonstrates usage in both configuration files and page objects for authenticated requests. ```typescript import { getEnvCredentials } from '@netanelh2/playwright-framework' // .env file // BASE_URL=https://staging.example.com // API_KEY=abc123 // DEFAULT_TIMEOUT=30000 // Usage in configuration export const BASE_URL = getEnvCredentials('BASE_URL') export const API_KEY = getEnvCredentials('API_KEY') export const DEFAULT_TIMEOUT = Number(getEnvCredentials('DEFAULT_TIMEOUT')) // Usage in page objects export class ApiPage extends BasePage { private readonly BASE_URL = getEnvCredentials('BASE_URL') private readonly API_KEY = getEnvCredentials('API_KEY') async navigateTo(path: string): Promise { await this.gotoURL(`${this.BASE_URL}${path}`) } async makeAuthenticatedRequest(): Promise { await this.page.setExtraHTTPHeaders({ 'Authorization': `Bearer ${this.API_KEY}`, }) } } ``` -------------------------------- ### Create Page Objects with Types (TypeScript) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/README.md Shows how to create page objects that extend a `BasePage` class and utilize type-safe locators. This pattern encapsulates page interactions, making tests more readable and reusable. It includes methods for filling fields, clicking elements, and validating visibility. ```typescript import {BasePage, type Page} from '@netanelh2/playwright-framework' import {test} from '../fixtures/testSetup' import {LOGIN_PAGE_LOCATORS as L} from '../locators/login/Login_Page' export class LoginPage extends BasePage { constructor(page: Page) { super(page) } async login(username: string, password: string): Promise { await test.step('User login flow', async () => { const usernameLocator = this.extractLocator(L.usernameField) const passwordLocator = this.extractLocator(L.passwordField) await usernameLocator.fill(username) await passwordLocator.fill(password) await this.clickOnElement(L.submitButton) }) } async validateLoaded(): Promise { await this.validateVisibility(L.usernameField) } } ``` -------------------------------- ### Type Imports from Framework (TypeScript) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Shows the specific type imports available from `@netanelh2/playwright-framework`, enabling developers to leverage the framework's type definitions for improved code safety and autocompletion. ```typescript // Type imports import type { StringOrRoleLocatorType, RoleLocator, AriaRole, Page, Locator, PageFixtures, } from '@netanelh2/playwright-framework' ``` -------------------------------- ### Package JSON Requirements for Playwright Framework Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Specifies the necessary package.json configurations for the Playwright Framework. It ensures the project is treated as an ES module and sets the minimum required versions for Node.js and npm. ```json { "type": "module", "engines": { "node": ">=18.0.0", "npm": ">=9.0.0" } } ``` -------------------------------- ### Test Fixture Import (TypeScript) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Illustrates how to import the base test fixture from `@netanelh2/playwright-framework`, which is necessary when defining custom test fixtures that extend the framework's capabilities. ```typescript // Test fixtures (for custom fixtures) import {test as baseTest} from '@netanelh2/playwright-framework' ``` -------------------------------- ### Define Type-Safe Locators with Playwright Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Demonstrates how to define centralized locators using a role-based pattern with type safety provided by `@netanelh2/playwright-framework`. This approach supports CSS selectors and automatic fallback, enhancing maintainability. ```typescript import type {StringOrRoleLocatorType} from '@netanelh2/playwright-framework' // Centralized locators with role-based pattern (preferred) export const LOGIN_PAGE_LOCATORS = { usernameField: {role: 'textbox', name: 'Username'}, passwordField: {role: 'textbox', name: 'Password'}, submitButton: {role: 'button', name: 'Sign In'}, errorMessage: '.error-message', } as const satisfies Record ``` -------------------------------- ### Define User Types and Test Data Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Shows how to define TypeScript interfaces for user credentials and export sample user data objects. This promotes type safety and organization for test data used in authentication scenarios. ```typescript // src/types/userTypes.ts export interface UserCredentials { username: string password: string role?: 'admin' | 'user' | 'guest' } // src/data/users.ts import type {UserCredentials} from '../types/userTypes' export const STANDARD_USER: UserCredentials = { username: 'standard_user', password: 'secret_sauce', role: 'user', } export const ADMIN_USER: UserCredentials = { username: 'admin', password: 'admin123', role: 'admin', } ``` -------------------------------- ### TypeScript Configuration for Playwright Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Recommended tsconfig.json for Playwright projects, ensuring optimal compatibility with modern JavaScript features and Playwright's testing environment. It specifies compiler options, included files, and excluded directories. ```json { "compilerOptions": { "target": "ES2022", "module": "ES2022", "lib": ["ES2022"], "moduleResolution": "bundler", "esModuleInterop": true, "strict": true, "skipLibCheck": true, "resolveJsonModule": true, "types": ["node", "@playwright/test"] }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] } ``` -------------------------------- ### Role-Based Locators with TypeScript Types Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Showcases the use of role-based locators, which are preferred for accessibility, using TypeScript types. This includes simple role locators, locators with parent contexts, and leveraging type safety for ARIA roles. These locators improve test robustness by relying on semantic HTML structure. ```typescript import type {RoleLocator, AriaRole} from '@netanelh2/playwright-framework' // Simple role locator const submitButton: RoleLocator = { role: 'button', name: 'Submit', } // Role locator with parent context const usernameInput: RoleLocator = { parent: '.login-form', role: 'textbox', name: 'Username', } // Available ARIA roles (type-safe) const heading: RoleLocator = { role: 'heading', name: 'Welcome', } ``` -------------------------------- ### CSS, XPath, and Text Locators in TypeScript Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Demonstrates the usage of basic string-based locators in TypeScript, including CSS selectors, XPath expressions, and text selectors. These are fundamental for targeting elements when role-based locators are not suitable or available. Ensure the selectors accurately target the desired HTML elements. ```typescript // CSS Selector const button = '#submit-button' const input = '.username-input' // XPath const element = '//button[@type="submit"]' // Text selector const link = 'text=Click Here' ``` -------------------------------- ### Extending BasePage for Page Objects (TypeScript) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Illustrates the best practice of extending the `BasePage` class from `@netanelh2/playwright-framework` to create page objects. This promotes a consistent structure and allows leveraging shared functionalities within page-specific classes. ```typescript import {BasePage, type Page} from '@netanelh2/playwright-framework' export class CheckoutPage extends BasePage { constructor(page: Page) { super(page) } // Your page-specific methods } ``` -------------------------------- ### Define Type-Safe Locators (TypeScript) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/README.md Demonstrates how to define type-safe locators using TypeScript. This approach centralizes locator definitions and leverages role-based locators for better maintainability and type checking within Playwright tests. ```typescript import type {StringOrRoleLocatorType} from '@netanelh2/playwright-framework' // Centralized locators with role-based pattern export const LOGIN_PAGE_LOCATORS = { usernameField: {role: 'textbox', name: 'Username'}, passwordField: {role: 'textbox', name: 'Password'}, submitButton: {role: 'button', name: 'Sign In'}, errorMessage: '.error-message', } as const satisfies Record ``` -------------------------------- ### Define Type-Safe Locators (Role-Based) Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Illustrates defining type-safe locators using the role-based pattern for enhanced maintainability and clarity. Supports centralized locators and scoped locators with parent contexts. ```typescript import type { StringOrRoleLocatorType } from '@netanelh2/playwright-framework' // Centralized locators with role-based pattern (recommended) export const LOGIN_PAGE_LOCATORS = { usernameField: { role: 'textbox', name: 'Username' }, passwordField: { role: 'textbox', name: 'Password' }, submitButton: { role: 'button', name: 'Sign In' }, errorMessage: '.error-message', rememberMe: { role: 'checkbox', name: 'Remember me' }, } as const satisfies Record // With parent context for scoped elements export const CHECKOUT_LOCATORS = { formSubmit: { parent: '.checkout-form', role: 'button', name: 'Complete Order', }, shippingAddress: { parent: '#shipping-section', role: 'textbox', name: 'Address', }, } as const satisfies Record ``` -------------------------------- ### Create Custom Playwright Fixtures with Type Safety Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Defines custom fixtures for `LoginPage` and `DashboardPage` by extending the base Playwright test object. This allows for dependency injection of page objects and ensures type safety within tests. ```typescript // src/fixtures/testSetup.ts import {test as baseTest} from '@netanelh2/playwright-framework' import {LoginPage} from '../pages/LoginPage' import {DashboardPage} from '../pages/DashboardPage' interface CustomFixtures { loginPage: LoginPage dashboardPage: DashboardPage } export const test = baseTest.extend({ loginPage: async ({page}, use) => { await use(new LoginPage(page)) }, dashboardPage: async ({page}, use) => { await use(new DashboardPage(page)) }, }) export {expect} from '@netanelh2/playwright-framework' ``` -------------------------------- ### Centralizing Locators in Page Object Files (TypeScript) Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Shows how to centralize locators for a specific page within a dedicated TypeScript file. This improves maintainability and readability by grouping all locators for a page in one place, using a type-safe approach. ```typescript // src/locators/checkout/Checkout_Page.ts import type {StringOrRoleLocatorType} from '@netanelh2/playwright-framework' export const CHECKOUT_PAGE_LOCATORS = { firstName: {role: 'textbox', name: 'First Name'}, lastName: {role: 'textbox', name: 'Last Name'}, continueButton: {role: 'button', name: 'Continue'}, } as const satisfies Record ``` -------------------------------- ### Environment Variables with Type Safety in TypeScript Source: https://github.com/netanelh2/playwright-framework-suite/blob/main/packages/playwright-framework/README.md Demonstrates how to securely load environment variables using `getEnvCredentials` for type-safe access to configuration values like base URLs and API keys. This is crucial for managing sensitive information and environment-specific settings in Playwright tests. ```typescript import {getEnvCredentials} from '@netanelh2/playwright-framework' // Load environment variables (from .env file) const baseUrl = getEnvCredentials('BASE_URL') const apiKey = getEnvCredentials('API_KEY') const timeout = getEnvCredentials('DEFAULT_TIMEOUT') // Usage in page objects export class ApiPage extends BasePage { private readonly BASE_URL = getEnvCredentials('BASE_URL') async navigateTo(path: string): Promise { await this.gotoURL(`${this.BASE_URL}${path}`) } } ``` -------------------------------- ### Array Utilities for Data Manipulation Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Illustrates the use of the `findItemByProperty` utility from '@netanelh2/playwright-framework' to efficiently search for objects within an array based on a specific property and value. It includes type definitions for clarity and shows practical application within test scenarios. ```typescript import { findItemByProperty } from '@netanelh2/playwright-framework' interface User { id: number email: string role: string status: 'active' | 'inactive' } const users: User[] = [ { id: 1, email: 'admin@test.com', role: 'admin', status: 'active' }, { id: 2, email: 'user@test.com', role: 'user', status: 'active' }, { id: 3, email: 'guest@test.com', role: 'guest', status: 'inactive' }, ] // Find user by email const admin = findItemByProperty(users, 'email', 'admin@test.com') // Returns: { id: 1, email: 'admin@test.com', role: 'admin', status: 'active' } // Find user by role const regularUser = findItemByProperty(users, 'role', 'user') // Returns: { id: 2, email: 'user@test.com', role: 'user', status: 'active' } // Find user by id const guestUser = findItemByProperty(users, 'id', 3) // Returns: { id: 3, email: 'guest@test.com', role: 'guest', status: 'inactive' } // Usage in tests test('should find and use specific user', async ({ loginPage }) => { const testUser = findItemByProperty(users, 'role', 'admin') await loginPage.login(testUser.email, 'password123') }) ``` -------------------------------- ### Using BasePage Validation Methods in TypeScript Source: https://context7.com/netanelh2/playwright-framework-suite/llms.txt Implements a `DashboardPage` class that extends `BasePage` from the framework to utilize built-in validation methods. It demonstrates validation of element visibility, text content, and URL using methods like `validateVisibility`, `validateText`, and `validateURL`. It also shows how to wait for specific element states with custom options. This promotes consistent and reliable assertions in tests. It depends on `BasePage`, `Page`, and locator definitions. ```typescript import { BasePage, type Page } from '@netanelh2/playwright-framework' import { DASHBOARD_LOCATORS as L } from '../locators/dashboard/Dashboard_Page' export class DashboardPage extends BasePage { constructor(page: Page) { super(page) } async validateLoaded(): Promise { // Validate element visibility await this.validateVisibility(L.header) await this.validateVisibility(L.userMenu) // Validate URL await this.validateURL('/dashboard') } async validateUserLoggedIn(username: string): Promise { // Validate element text content await this.validateText(L.welcomeMessage, `Welcome, ${username}`) } async validateElementState(): Promise { // Wait for element state with custom options await this.waitForSelectorState('.loading-spinner', { state: 'hidden' }) await this.waitForSelectorState('.data-table', { state: 'visible' }) } } ```