Pages

Wednesday, 2 October 2024

Introduction to Web Testing with Playwright

 Introduction to Web Testing with Playwright



📌 Telegram Group: https://t.me/+FTf_NPb--GQ2ODhl
📌 YouTube channel: https://lnkd.in/gGUGmb-P

******


1. What is Playwright?

Playwright is an open-source framework developed by Microsoft for automating web browser interactions. It enables developers and testers to write scripts for browser automation and end-to-end testing in a consistent and reliable manner. With support for multiple browsers (Chromium, Firefox, and WebKit), Playwright offers a robust solution for modern web testing needs.

2. Key Features of Playwright

  • Cross-Browser Testing: Supports multiple browsers including Chromium, Firefox, and WebKit, ensuring your web application works consistently across different environments.

  • Auto-Waiting: Automatically waits for elements to be ready before interacting with them, reducing the need for manual waits and improving test reliability.

  • Network Interception: Allows for mocking and intercepting network requests, enabling comprehensive testing of your application’s interaction with APIs.

  • Headless Mode: Supports headless browser testing, which is useful for continuous integration environments where a graphical user interface is not available.

  • Parallel Execution: Facilitates running tests in parallel, speeding up test execution and improving efficiency.


Playwright vs Selenium
















Type of Web Application/Project


Why Playwright Excels


Key Playwright Features


Key Problems with Selenium


Time Saved with Playwright (Approx.)


Single Page Applications (SPAs)


Better handling of dynamic content and JavaScript-heavy rendering


Auto-waiting, network interception, and synchronization


Requires custom waits and manual synchronization


20-30% reduction in scripting time


Cross-Browser Testing


Consistent testing across multiple browsers with a single API


Supports Chromium, Firefox, WebKit


Requires setting up different browser drivers


10-20% reduction due to easier setup


End-to-End (E2E) Testing


Effective testing of complex user interactions and workflows


Detailed tracing, debugging tools


Needs additional tools for tracing and debugging


15-25% reduction in debugging/maintenance


Performance and Visual Testing


Captures performance metrics and visual regressions effectively


Screenshot comparison, performance measurement tools


Requires integration with third-party tools with PAID versions


10-15% reduction in setup and execution


API-Integrated Testing


Allows testing of both frontend and backend within the same framework


Integrated API testing alongside UI testing


Requires separate frameworks for API testing


20-30% reduction in API-related tests


Modern Web Features


Better handling of advanced web features like Shadow DOM


Support for Shadow DOM, geolocation, WebSockets


Limited support, often requires workarounds


15-20% reduction in handling web elements


Mobile and Responsive Testing


Direct testing of mobile emulation and responsive designs


Mobile device emulation, responsive design testing


Requires additional configurations for mobile emulation


15-20% reduction in setup/execution time


Security Testing


Better control over authentication, cookies, and session management


Manipulation of security features, validation tools


Manual setup for security-related tests


10-15% reduction in testing/validation


Real-Time Applications


Advanced handling of real-time data and dynamic content updates


WebSocket communication, network event handling


More manual handling of WebSocket and dynamic content


15-25% reduction in implementation/maintenance



3. Setting Up Playwright


How to Install Node.js on Windows and Mac

For Windows:

  1. Download Node.js:

    • Visit the official Node.js website.

    • Download the Windows Installer (recommended for most users).

  2. Install Node.js:

    • Run the downloaded .msi installer file.

    • Follow the setup wizard instructions.

      • Make sure to check the box that says "Automatically install the necessary tools" (this will install npm and other tools).

    • Once the installation is complete, Node.js and npm (Node Package Manager) will be installed on your system.

  3. Verify Installation:

Open Command Prompt and type:


node -v

  • This will display the installed version of Node.js.

To check npm, type:


npm -v


  1. Optional – Install Visual Studio Build Tools:

    • For some npm packages that require native compilation, you may need to install Visual Studio Build Tools.

The Node.js installer will give you an option to install the required tools. If you missed it, you can manually install them by running the following in the command prompt:


npm install --global windows-build-tools


For macOS:

  1. Install Node.js using Homebrew (recommended):

    • Open Terminal.

Install Homebrew (if not already installed):


/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"


After Homebrew is installed, use it to install Node.js:


brew install node


  1. Download Node.js (Alternative Option):

    • If you don’t want to use Homebrew, you can download the macOS installer directly from the Node.js website.

    • Download the .pkg file for macOS and run the installer.

  2. Verify Installation:

After the installation is complete, open the Terminal and check the installed Node.js version:

node -v


To check npm, run:

npm -v


Now, Node.js and npm are ready to use on both Windows and macOS!


To start using Playwright, follow these steps:

Install Playwright:
You can install Playwright via npm (Node.js package manager). Open your terminal and run:


npm install -D @playwright/test


Install Browsers:
Playwright can install necessary browser binaries automatically. Run:

npx playwright install


Create a Test File:
Create a new file, say example.test.js, and write your first test:


const { test, expect } = require('@playwright/test');

test('basic test example', async ({ page }) => {
  await page.goto('https://example.com');
  await expect(page).toHaveTitle('Example Domain');
});


Run Your Tests:
Execute your test using:

npx playwright test


4. Writing Your First Test

Let’s dive into a basic example to understand how Playwright works.


const { test, expect } = require('@playwright/test');

test('should display the correct title', async ({ page }) => {
  await page.goto('https://example.com');
  const title = await page.title();
  expect(title).toBe('Example Domain');
});


Explanation:

  • test is a function provided by Playwright to define a test case.

  • page.goto() navigates to the specified URL.

  • page.title() retrieves the title of the page.

  • expect is used for assertions to validate test outcomes.

5. Handling Web Elements

Playwright provides various methods to interact with web elements:

Clicking a Button:


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


Filling a Form:


await page.fill('input[name="username"]', 'testuser');
await page.fill('input[name="password"]', 'password123');


Selecting a Dropdown Option:

await page.selectOption('select#country', 'USA');


Getting Text from an Element:


const text = await page.textContent('h1');
expect(text).toBe('Welcome');


6. Advanced Features

Network Interception and Mocking:
You can intercept network requests to test different scenarios:


await page.route('**/api/*', route => route.fulfill({
  contentType: 'application/json',
  body: JSON.stringify({ success: true })
}));


Screenshots and Videos:
Capture screenshots or record videos of test runs for debugging:


await page.screenshot({ path: 'screenshot.png' });

await page.video().saveAs('video.mp4');

Parallel Test Execution:
Run tests in parallel to speed up the testing process. Configure this in the playwright.config.js file.

7. Best Practices

  • Use Page Object Model (POM): Organise your tests by separating page-specific code into separate classes.

  • Keep Tests Independent: Ensure tests do not depend on each other’s outcomes.

  • Use CI/CD Integration: Integrate Playwright tests with your continuous integration/continuous deployment (CI/CD) pipelines for automated testing.

8. Conclusion

Playwright is a powerful tool for web testing, providing comprehensive features to handle modern web applications effectively. Its support for multiple browsers, auto-waiting, network interception, and parallel execution makes it an excellent choice for end-to-end testing. By following best practices and utilising Playwright's advanced features, you can ensure robust and reliable testing of your web applications.

9. Q&A

Feel free to ask any questions or share your experiences with web testing and Playwright!



10. Where to learn ?
https://learn.microsoft.com/en-us/training/modules/build-with-playwright/


Connect with me over a 1:1 call: https://topmate.io/sidharth_shukla/
YouTube: https://www.youtube.com/@automatewithsidharth
Learn GEN-AI For Software Testing: https://topmate.io/sidharth_shukla/411804 


👉 Complete Interview Q&A Package to crack interviews for Automation Testing and SDET with similar exampleshttps://lnkd.in/gJrBGExe : Highest Rating

💚 Want to discuss on the same or need help in 1:1 career guidance for SDET or Automation, reach out to me here: https://lnkd.in/dF5ADMiU

💚 One-on-one guided session on automation & SDET: (API ( Postman / RestAssured)+ UI(Selenium)+ Mobile(Appium)+ DevOps(Jenkins,GIT,Docker)+ Doubt/MockInterviews) + Interview Q&A Package : https://lnkd.in/gJ-fQQ-W

^^^^^^^^^^^^

For additional interview Q&A scenarios, check out the document here: https://lnkd.in/gJrBGExe

Masterclass in Test Automation with 1:1 guidance: https://topmate.io/sidharth_shukla/110008

***


No comments:

Post a Comment