LayoutTitle

Hoverable Dropdown

Showing posts with label npm. Show all posts
Showing posts with label npm. Show all posts

Sunday, September 28, 2025

Playwright with JavaScript/TypeScript – Complete Setup Guide

 

1. Installation & Prerequisites

🔹 Prerequisites

  • Node.js (≥16.x)Download

  • npm (comes with Node.js) or yarn

🔹 Install Playwright Project

# Create new folder mkdir playwright_project && cd playwright_project # Initialize npm project npm init -y # Install Playwright Test (JS + TS support built-in) npm install -D @playwright/test # Install browsers npx playwright install

✅ This sets up Chromium, Firefox, WebKit for Playwright.


2. Configuration

🔹 Project Structure

playwright_project/ │── tests/ │ ├── example.spec.ts │── playwright.config.ts │── package.json │── tsconfig.json

🔹 Create Playwright Config

playwright.config.ts

import { defineConfig, devices } from '@playwright/test'; export default defineConfig({ testDir: './tests', timeout: 30 * 1000, retries: 1, reporter: [['html', { open: 'never' }]], use: { baseURL: 'https://www.google.com', headless: true, screenshot: 'only-on-failure', video: 'retain-on-failure', }, projects: [ { name: 'chromium', use: { ...devices['Desktop Chrome'] }, }, { name: 'firefox', use: { ...devices['Desktop Firefox'] }, }, { name: 'webkit', use: { ...devices['Desktop Safari'] }, }, ], });

🔹 Add TypeScript Support

tsconfig.json

{ "compilerOptions": { "target": "ESNext", "module": "CommonJS", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "outDir": "dist" } }

3. Development (Writing Tests)

🔹 Example Test (TS)

tests/example.spec.ts

import { test, expect } from '@playwright/test'; test('Google search example', async ({ page }) => { await page.goto('https://www.google.com'); await page.fill('textarea[name="q"]', 'Playwright Test Automation'); await page.keyboard.press('Enter'); await expect(page).toHaveTitle(/Playwright/); });

4. Execution & Reporting

🔹 Run Tests

# Run all tests npx playwright test # Run in headed mode (visible browser) npx playwright test --headed # Run specific test file npx playwright test tests/example.spec.ts # Run with Chromium only npx playwright test --project=chromium

🔹 Open HTML Report

npx playwright show-report

5. Jenkins CI/CD Integration

🔹 Jenkins Prerequisites

  • Install Jenkins (Download)

  • Plugins: NodeJS, Git, HTML Publisher

🔹 Jenkins Job (Pipeline)

  1. Create a Pipeline job in Jenkins.

  2. Configure NodeJS tool installation (global config).

  3. Add Jenkinsfile to your repo:

pipeline { agent any tools { nodejs "NodeJS_16" // Configure this in Jenkins } stages { stage('Checkout') { steps { git branch: 'main', url: 'https://github.com/your-repo/playwright_project.git' } } stage('Install Dependencies') { steps { sh 'npm ci' sh 'npx playwright install' } } stage('Run Tests') { steps { sh 'npx playwright test --reporter=html' } } } post { always { publishHTML(target: [ reportDir: 'playwright-report', reportFiles: 'index.html', keepAll: true, reportName: 'Playwright Test Report' ]) } } }

6. Scaling & Best Practices

  • Page Object Model (POM): Organize locators & actions in classes.

  • Fixtures: Use Playwright fixtures to share browser/page.

  • Parallel Tests: Built-in with Playwright (projects[]).

  • Environment Configs: Create multiple configs for dev, staging, prod.

  • Dockerize Tests: For portability in CI.

  • Cloud Execution: Use BrowserStack / Sauce Labs for real devices.


7. Real-World Example

📌 Automate an e-commerce flow:

  1. Login

  2. Search for product

  3. Add to cart

  4. Checkout

  5. Assert confirmation

Run tests in:

  • Chromium (desktop)

  • WebKit (Safari mobile emulation)

  • Firefox

All in parallel via Jenkins.


Summary for a Test Automation Engineer:

  1. Install Node.js + Playwright (npm install -D @playwright/test)

  2. Configure project (playwright.config.ts, tsconfig.json)

  3. Develop tests in TypeScript (preferred for large frameworks)

  4. Execute locally (npx playwright test) + view reports

  5. Integrate with Jenkins CI/CD (pipeline + HTML reports)

  6. Scale with POM, Docker, Cloud, Parallel execution

Playwright with Python – Complete Setup & CI/CD Guide

 

1. Installation

🔹 Prerequisites

  • Install Python (≥3.8)Download

  • Install Node.js (≥16) (needed for browsers) → Download

🔹 Install Playwright

# Create project folder mkdir playwright_automation && cd playwright_automation # Create virtual environment python -m venv venv source venv/bin/activate # Linux/Mac venv\Scripts\activate # Windows # Install Playwright pip install pytest pytest-playwright # Install browsers playwright install

✅ This installs Chromium, Firefox, and WebKit engines for Playwright.


2. Configuration

🔹 Project Structure

playwright_automation/ │── tests/ │ ├── test_google.py │── conftest.py │── requirements.txt │── pytest.ini
  • tests/ → contains test cases

  • conftest.py → pytest fixtures (e.g., browser setup)

  • requirements.txt → dependencies

🔹 requirements.txt

pytest pytest-playwright

🔹 pytest.ini

[pytest] addopts = -v --headed --html=report.html --self-contained-html markers = smoke: quick checks regression: full suite

3. First Test (Development)

Create tests/test_google.py:

import pytest from playwright.sync_api import sync_playwright def test_google_search(): with sync_playwright() as p: browser = p.chromium.launch(headless=True) page = browser.new_page() page.goto("https://www.google.com") page.fill("input[name='q']", "Playwright Python") page.keyboard.press("Enter") assert "Playwright" in page.title() browser.close()

Run test:

pytest tests/ --headed
  • --headed → shows browser UI

  • Default is headless (faster)


4. Advanced Setup

🔹 Using Pytest Fixtures (Reusable Browsers)

Create conftest.py:

import pytest from playwright.sync_api import sync_playwright @pytest.fixture(scope="session") def browser(): playwright = sync_playwright().start() browser = playwright.chromium.launch(headless=True) yield browser browser.close() playwright.stop() @pytest.fixture def page(browser): context = browser.new_context() page = context.new_page() yield page context.close()

Now tests/test_google.py becomes:

def test_google_search(page): page.goto("https://www.google.com") page.fill("input[name='q']", "Playwright Python") page.keyboard.press("Enter") assert "Playwright" in page.title()

5. Execution

🔹 Run All Tests

pytest --headed --html=report.html

🔹 Run Specific Marker

pytest -m "smoke"

🔹 Parallel Execution

pytest -n 4

6. Jenkins CI/CD Integration

🔹 Step 1: Install Jenkins

🔹 Step 2: Jenkins Job

  1. Create a Pipeline Job

  2. Configure Git repo (with Playwright project)

  3. Add build steps:

# Inside Jenkins pipeline pip install -r requirements.txt playwright install pytest --html=report.html --self-contained-html
  1. Post-build actions → Publish HTML report:

    • HTML directory: .

    • Index page: report.html


🔹 Jenkinsfile (Pipeline as Code)

Place this in your repo:

pipeline { agent any stages { stage('Setup') { steps { sh 'python -m venv venv' sh '. venv/bin/activate && pip install -r requirements.txt' sh '. venv/bin/activate && playwright install' } } stage('Test') { steps { sh '. venv/bin/activate && pytest --html=report.html --self-contained-html' } } } post { always { publishHTML (target: [ reportDir: '.', reportFiles: 'report.html', keepAll: true, reportName: 'Playwright Test Report' ]) } } }

7. Scaling Up

  • Cross-browser execution:

    pytest --browser firefox pytest --browser webkit
  • Parallel test execution: pytest -n auto

  • Cloud Testing: Integrate with BrowserStack/Sauce Labs

  • Reporting: Allure Reports (pip install allure-pytest)

  • Dockerize your test framework for portability


8. Real-World Project Idea

📌 Automate an e-commerce site workflow with Playwright:

  • Search → Add to cart → Checkout → Validate order in DB

  • Cover UI + API + DB layers

  • Integrate with Jenkins for nightly regression runs


In summary:

  1. Install Python + Playwright

  2. Set up virtual environment + pytest config

  3. Write first test (test_google.py)

  4. Build framework with fixtures & POM

  5. Run tests locally + in parallel

  6. Integrate with Jenkins pipeline (CI/CD)

  7. Scale with reporting, Docker, Cloud execution

Python Test Automation Engineer: Complete Setup Guide

 

1. Install Python

🔹 Steps:

  1. Download Python (latest stable, e.g., 3.12.x)
    👉 https://www.python.org/downloads/

  2. During installation:

    • ✅ Check “Add Python to PATH”

    • ✅ Install pip (package manager)

  3. Verify installation:

    python --version pip --version

2. Set Up Environment

🔹 Virtual Environment

Always isolate projects using venv or pipenv.

# Create virtual environment python -m venv venv # Activate (Windows) venv\Scripts\activate # Activate (Linux/Mac) source venv/bin/activate

You should see (venv) in your terminal.

🔹 Install Core Packages

pip install pytest selenium requests pytest-html

Optional (for advanced use):

pip install allure-pytest pytest-xdist

3. Start with a Small Example

🔹 Web Automation Example (Selenium + pytest)

  1. Install browser driver (e.g., ChromeDriver).

  2. Create test_google.py:

from selenium import webdriver from selenium.webdriver.common.by import By def test_google_search(): driver = webdriver.Chrome() driver.get("https://www.google.com") search_box = driver.find_element(By.NAME, "q") search_box.send_keys("Python Test Automation") search_box.submit() assert "Python" in driver.title driver.quit()
  1. Run test:

pytest -v --html=report.html

👉 Generates report.html with results.


4. API Automation Example (pytest + requests)

Create test_api.py:

import requests def test_github_api(): response = requests.get("https://api.github.com") assert response.status_code == 200 assert "current_user_url" in response.json()

Run:

pytest -v

5. Build a Mini Automation Framework (Skeleton)

Project Structure:

automation/ │── tests/ │ ├── test_ui.py │ ├── test_api.py │── pages/ │ ├── base_page.py │ ├── login_page.py │── utils/ │ ├── config.py │ ├── logger.py │── conftest.py │── requirements.txt │── pytest.ini
  • tests/ → UI + API test cases

  • pages/ → Page Object Model for UI

  • utils/ → Config, helpers

  • conftest.py → pytest fixtures

  • pytest.ini → markers, test configs

✅ This is a reusable base for real projects.


6. Integrate with CI/CD

🔹 Option A: Jenkins

  1. Install Jenkins (download)

  2. Install plugins:

    • Git Plugin

    • Pytest Plugin (or Allure)

  3. Create a Jenkins Job:

    • Pull code from GitHub

    • Add build step:

      pip install -r requirements.txt pytest -v --html=report.html
    • Archive report.html as test report.


🔹 Option B: GitHub Actions

  1. In your repo, create .github/workflows/python-tests.yml:

name: Python Test Automation on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.12' - name: Install dependencies run: | pip install -r requirements.txt - name: Run Tests run: pytest -v --html=report.html
  1. Push code → GitHub Actions runs tests automatically.


7. Scaling Up

  • Add parallel execution: pytest -n 4 (with pytest-xdist)

  • Add cross-browser testing: BrowserStack/Sauce Labs integration

  • Add Allure Reports for rich reporting

  • Add Dockerfile to containerize the framework


Summary Roadmap

  1. Install Python + pip + venv

  2. Install pytest, selenium, requests

  3. Write UI & API tests

  4. Create framework structure

  5. Integrate with CI/CD (Jenkins/GitHub Actions)

  6. Scale with parallel execution, cloud, reporting

Python Test Automation Engineer Roadmap (End-to-End Guide)

1. Foundations

🔑 Goal: Build strong basics in software testing & Python.

Core Skills

  • Testing Fundamentals

    • SDLC, STLC, Agile/Scrum

    • Test case design techniques (boundary, equivalence, pairwise, OAT, etc.)

    • Manual testing basics (functional, regression, smoke, UAT)

  • Python Programming

    • Syntax, variables, loops, functions, OOP

    • File handling, JSON, CSV

    • Exception handling, logging

    • Virtual environments (venv, pipenv)

Practice: Write Python scripts to:

  • Read test data from Excel/CSV

  • Automate repetitive manual test cases

  • Generate simple reports


2. Version Control & CI/CD

🔑 Goal: Learn collaboration & automation pipelines.

  • Git & GitHub/GitLab/Bitbucket

    • Branching, merging, pull requests

  • CI/CD Tools

    • Jenkins, GitHub Actions, GitLab CI

  • Docker (Basics)

    • Containerize your test framework

Practice:

  • Push a test script to GitHub.

  • Set up Jenkins to run it on every push.


3. Test Automation with Python

🔑 Goal: Automate web, API, and data-driven tests.

Web Testing

  • Selenium with Python

    • Locators (XPath, CSS)

    • Page Object Model (POM)

    • Waits, Alerts, Frames

    • Headless execution

  • Playwright (modern alternative)

API Testing

  • Python requests module

  • Postman → Newman → Python wrappers

  • API frameworks: pytest + requests

  • Validate JSON schema, status codes, headers

Database Testing

  • Connect Python with DBs (pyodbc, psycopg2, sqlalchemy)

  • Write tests for CRUD operations

Practice Projects:

  • Automate login, search, checkout flow of an e-commerce site.

  • Build pytest-based API tests for a sample REST API.

  • Validate DB entries after API/web actions.


4. Test Frameworks & Best Practices

🔑 Goal: Write scalable, maintainable automation frameworks.

  • pytest (must-know)

    • Fixtures

    • Parametrization

    • Markers (smoke, regression)

    • Plugins (pytest-html, pytest-xdist)

  • unittest (legacy, less popular but useful)

  • Framework Patterns

    • Page Object Model (POM)

    • Data-Driven Testing

    • Keyword-Driven Testing

    • BDD (Behavior-Driven Development) → behave or pytest-bdd

Practice:

  • Build a hybrid test automation framework using Python + pytest + Selenium.

  • Generate HTML/Allure reports.

  • Run tests in parallel.


5. DevOps + Cloud + Scaling

🔑 Goal: Run tests in pipelines, cloud, and at scale.

  • CI/CD Integration (Jenkins/GitHub Actions + pytest)

  • Dockerize Automation Framework

  • Cloud Execution:

    • Selenium Grid, BrowserStack, Sauce Labs

    • Playwright on GitHub Actions

Practice:

  • Run Selenium tests on BrowserStack with different browsers.

  • Execute Playwright tests in GitHub Actions with matrix builds.


6. Advanced Test Automation

🔑 Goal: Go beyond UI/API basics.

  • Performance Testing

    • JMeter / Locust (Python-based load testing)

  • Security Testing Basics

    • OWASP ZAP automation with Python

  • Mobile Testing

    • Appium + Python

  • Contract Testing

    • Pact (for microservices)


7. Supporting Tools & Skills

🔑 Goal: Become a “Full-stack QA Engineer.”

  • Test Management: Jira, Xray, TestRail

  • Bug Tracking: Jira, Bugzilla

  • Monitoring Logs: ELK stack, Grafana basics

  • Agile QA Role: Writing test strategies, automation strategy docs


8. Real-World Projects (Portfolio)

Build at least 3–5 solid projects to showcase:

  1. Web Automation Framework:

    • Python + Selenium + pytest + POM

    • HTML/Allure reports + parallel execution

  2. API Testing Framework:

    • Python + requests + pytest + JSON schema validation

    • CI/CD with Jenkins

  3. Hybrid Framework (UI + API + DB):

    • End-to-end tests for a sample e-commerce flow

  4. Performance Testing (Locust/JMeter):

    • Load test login and checkout APIs

  5. Mobile Automation:

    • Appium + Python tests for Android/iOS app


9. Soft Skills & Career Growth

  • Documentation: Write clear test cases, automation strategy, reports

  • Communication: Collaborate with developers, product managers

  • Problem-Solving: Debugging automation failures efficiently

  • Continuous Learning: AI in testing (Testim, Mabl), new frameworks


10. Roadmap Timeline

⏳ Suggested timeline (if starting fresh):

  • Month 1–2: Python + Testing fundamentals

  • Month 3–4: Selenium + API + pytest basics

  • Month 5–6: Framework building + Git + CI/CD

  • Month 7–8: Advanced topics (BDD, Docker, Cloud)

  • Month 9–12: Real-world projects + interview prep


11. Career Path

  • Junior Automation Engineer → Automates basic test cases.

  • Test Automation Engineer → Builds frameworks, CI/CD integration.

  • Senior QA Engineer → Leads automation strategy, mentors juniors.

  • SDET (Software Development Engineer in Test) → Strong coding + testing mix, contributes to dev pipelines.

  • QA Architect → Designs enterprise-wide automation solutions.


In summary:

  • Start with Python + Testing basics,

  • Master pytest + Selenium + API automation,

  • Move to framework building + CI/CD + Cloud execution,

  • Add performance, mobile, and advanced skills,

  • Build a portfolio of real projects to stand out.