Playwright with JavaScript Commands -Part3

 

Advanced Playwright concepts with detailed explanations and syntax examples:


19. Debugging Tools

Playwright Inspector

 

 

npx playwright test –debug

 

  • What it does: Launches a visual debugger that lets you:
    • Pause/resume test execution
    • Step through commands one-by-one
    • Inspect elements, network requests, and console logs
  • Usage: Run this in your terminal to debug specific tests

Trace Viewer

 

 

// playwright.config.js

module.exports = {

  use: {

    trace: 'on-first-retry',

  }

};

 

  • What it does: Records test execution data (screenshots, network logs)
  • Syntax explanation:
    • trace: 'on-first-retry': Records only when tests fail and retry
    • Other options: 'on' (always), 'off' (never)
  • View traces:

 

 

npx playwright show-trace trace.zip


20. Custom Reporters

HTML Reporter Configuration

 

 

// playwright.config.js

module.exports = {

  reporter: [

    ['html', { outputFolder: 'my-reports' }]

  ]

};

 

  • What it does: Generates visual HTML test reports
  • Key files:
    • index.html: Test overview
    • Individual test traces and screenshots

21. CI/CD Integration

GitHub Actions Example

yaml

 

name: Playwright Tests

on: [push]

 

jobs:

  test:

    runs-on: ubuntu-latest

    steps:

      - uses: actions/checkout@v4

      - uses: actions/setup-node@v3

        with: { node-version: 18 }

      - run: npm ci

      - run: npx playwright install --with-deps

      - run: npx playwright test

  • Step breakdown:

1.      Check out repository code

2.      Set up Node.js environment

3.      Install project dependencies

4.      Install Playwright browsers

5.      Run tests


22. Page Object Model (POM)

Implementation Example

 

 

// models/LoginPage.js

class LoginPage {

  constructor(page) {

    this.page = page;

    this.username = page.locator('#username');

    this.password = page.locator('#password');

  }

 

  async login(user, pass) {

    await this.username.fill(user);

    await this.password.fill(pass);

    await this.page.click('text=Submit');

  }

}

 

// test.spec.js

test('Login test', async ({ page }) => {

  const loginPage = new LoginPage(page);

  await loginPage.login('admin', 'password');

});

  • Benefits:
    • Reusable components
    • Cleaner test files
    • Easier maintenance

23. Visual Testing

Screenshot Comparison

 

 

await expect(page).toHaveScreenshot('homepage.png');

 

  • What it does: Compares current page with baseline screenshot
  • First run: Creates reference screenshot
  • Subsequent runs: Detects visual differences
  • Configure in playwright.config.js:

 

 

expect: {

  toHaveScreenshot: {

    maxDiffPixels: 1000, // Allowable differences

  }

}


24. Authentication Strategies

Reuse Login State

 

 

// Save authentication state

const storage = await context.storageState({ path: 'auth.json' });

 

// Reuse in new tests

const context = await browser.newContext({

  storageState: 'auth.json'

});

 

  • How it works: Stores cookies/localStorage
  • Benefits: Avoid repeated login steps

25. Parallel Execution

 

 

// playwright.config.js

module.exports = {

  workers: 4 // Number of parallel threads

};

 

  • CLI override:

 

 

npx playwright test --workers 4

  • Best practice: Use 50-75% of available CPU cores

26. Environment Variables

Using .env Files

 

 

// .env

BASE_URL=https://staging.example.com

 

// test.spec.js

require('dotenv').config();

await page.goto(process.env.BASE_URL);

  • Setup:

 

 

npm install dotenv


27. Mocking Time

 

 

await page.addInitScript(() => {

  Date.now = () => new Date('2024-01-01').getTime();

});

  • What it does: Overrides system time for tests
  • Use cases:
    • Testing time-sensitive features
    • Bypassing expiration dates

28. Error Handling

 

 

try {

  await page.click('button#submit');

} catch (error) {

  console.log('Submit failed:', error);

  await page.screenshot('error.png');

}

  • Key concepts:
    • try: Attempt to execute code
    • catch: Handle errors gracefully
    • Always include cleanup steps in error handling

Key Javascript Concepts

1.      ES6 Classes (Used in Page Objects):

 

 

class LoginPage {

  constructor(page) { ... }

}

2.      Modules:

 

 

// Export

module.exports = { LoginPage };

 

// Import

const { LoginPage } = require('./models/LoginPage');

3.      Async/Await:

 

 

async function test() {

  await page.click();

}


Where to Go Next:

1.      Start with basic test scenarios

2.      Gradually incorporate advanced features

3.      Explore Playwright's official documentation

 

Post a Comment

0 Comments