Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 23, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 23, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 23, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 23, 2025

      SteamOS is officially not just for Steam Deck anymore — now ready for Lenovo Legion Go S and sort of ready for the ROG Ally

      May 23, 2025

      Microsoft’s latest AI model can accurately forecast the weather: “It doesn’t know the laws of physics, so it could make up something completely crazy”

      May 23, 2025

      OpenAI scientists wanted “a doomsday bunker” before AGI surpasses human intelligence and threatens humanity

      May 23, 2025

      My favorite gaming service is 40% off right now (and no, it’s not Xbox Game Pass)

      May 23, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      A timeline of JavaScript’s history

      May 23, 2025
      Recent

      A timeline of JavaScript’s history

      May 23, 2025

      Loading JSON Data into Snowflake From Local Directory

      May 23, 2025

      Streamline Conditional Logic with Laravel’s Fluent Conditionable Trait

      May 23, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      SteamOS is officially not just for Steam Deck anymore — now ready for Lenovo Legion Go S and sort of ready for the ROG Ally

      May 23, 2025
      Recent

      SteamOS is officially not just for Steam Deck anymore — now ready for Lenovo Legion Go S and sort of ready for the ROG Ally

      May 23, 2025

      Microsoft’s latest AI model can accurately forecast the weather: “It doesn’t know the laws of physics, so it could make up something completely crazy”

      May 23, 2025

      OpenAI scientists wanted “a doomsday bunker” before AGI surpasses human intelligence and threatens humanity

      May 23, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Playwright Mobile Automation for Seamless Web Testing

    Playwright Mobile Automation for Seamless Web Testing

    April 3, 2025

    Playwright is a fast and modern testing framework known for its efficiency and automation capabilities. It is great for web testing, including Playwright Mobile Automation, which provides built-in support for emulating real devices like smartphones and tablets. Features like custom viewports, user agent simulation, touch interactions, and network throttling help create realistic mobile testing environments without extra setup. Unlike Selenium and Appium, which rely on third-party tools, Playwright offers native mobile emulation and faster execution, making it a strong choice for testing web applications on mobile browsers. However, Playwright does not support native app testing for Android or iOS, as it focuses only on web browsers and web views.

    Playwright Mobile Automation

    In this blog, the setup process for mobile web automation in Playwright will be explained in detail. The following key aspects will be covered:

    • Emulating Mobile Devices
    • Using Custom Mobile Viewports
    • Real Device Setup & Execution

    Before proceeding with mobile web automation, it is essential to ensure that Playwright is properly installed on your machine. In this section, a step-by-step guide will be provided to help set up Playwright along with its dependencies. The installation process includes the following steps:

    Setting Up Playwright

    Before starting with mobile web automation, ensure that you have Node.js installed on your system. Playwright requires Node.js to run JavaScript-based automation scripts.

    1. Verify Node.js Installation

    To check if Node.js is installed, open a terminal or command prompt and run:

    node -v
    

    If Node.js is installed, this command will return the installed version. If not, download and install the latest version from the official Node.js website.

    2. Install Playwright and Its Dependencies

    Once Node.js is set up, install Playwright using npm (Node Package Manager) with the following commands:

    
    npm install @playwright/test
    
    npx playwright install
    
    
    • The first command installs the Playwright testing framework.
    • The second command downloads and installs the required browser binaries, including Chromium, Firefox, and WebKit, to enable cross-browser testing.

    3. Verify Playwright Installation

    To ensure that Playwright is installed correctly, you can check its version by running:

    
    npx playwright --version
    
    

    This will return the installed Playwright version, confirming a successful setup.

    4. Initialize a Playwright Test Project (Optional)

    If you plan to use Playwright’s built-in test framework, initialize a test project with:

    
    npx playwright test --init
    
    

    This sets up a basic folder structure with example tests, Playwright configurations, and dependencies.

    Once Playwright is installed and configured, you are ready to start automating mobile web applications. The next step is configuring the test environment for mobile emulation.

    Emulating Mobile Devices

    Playwright provides built-in mobile device emulation, enabling you to test web applications on various popular devices such as Pixel 5, iPhone 12, and Samsung Galaxy S20. This feature ensures that your application behaves consistently across different screen sizes, resolutions, and touch interactions, making it an essential tool for responsive web testing.

    1. Understanding Mobile Device Emulation in Playwright

    Playwright’s device emulation is powered by predefined device profiles, which include settings such as:

    • Viewport size (width and height)
    • User agent string (to simulate mobile browsers)
    • Touch support
    • Device scale factor
    • Network conditions (optional)

    These configurations allow you to mimic real mobile devices without requiring an actual physical device.

    2. Example Code for Emulating a Mobile Device

    Here’s an example script that demonstrates how to use Playwright’s mobile emulation with the Pixel 5 device:

    
    const { test, expect, devices } = require('@playwright/test');
    
    
    // Apply Pixel 5 emulation settings
    
    test.use({ ...devices['Pixel 5'] });
    
    
    test('Verify page title on mobile', async ({ page }) => {
    
        // Navigate to the target website
    
        await page.goto('https://playwright.dev/');
    
    
        // Simulate a short wait time for page load
    
        await page.waitForTimeout(2000);
    
    
        // Capture a screenshot of the mobile view
    
        await page.screenshot({ path: 'pixel5.png' });
    
    
        // Validate the page title to ensure correct loading
    
        await expect(page).toHaveTitle("Fast and reliable end-to-end testing for modern web apps | Playwright");
    
    });
    
    

    3. How This Script Works

    • It imports test, expect, and devices from Playwright.
    • The test.use({…devices[‘Pixel 5’]}) method applies the Pixel 5 emulation settings.
    • The script navigates to the Playwright website.
    • It waits for 2 seconds, simulating real user behavior.
    • A screenshot is captured to visually verify the UI appearance on the Pixel 5 emulation.
    • The script asserts the page title, ensuring that the correct page is loaded.

    4. Running the Script

    Save this script in a test file (e.g., mobile-test.spec.js) and execute it using the following command:

    
    npx playwright test mobile-test.spec.js
    
    

    If Playwright is set up correctly, the test will run in emulation mode and generate a screenshot named pixel5.png in your project folder.

    Playwright Mobile Automation for Seamless Web Testing

    5. Testing on Other Mobile Devices

    To test on different devices, simply change the emulation settings:

    
    test.use({ ...devices['iPhone 12'] }); // Emulates iPhone 12
    
    test.use({ ...devices['Samsung Galaxy S20'] }); // Emulates Samsung Galaxy S20
    
    

    Playwright includes a wide range of device profiles, which can be found by running:

    
    npx playwright devices
    
    

    Using Custom Mobile Viewports

    Playwright provides built-in mobile device emulation, but sometimes your test may require a device that is not available in Playwright’s predefined list. In such cases, you can manually define a custom viewport, user agent, and touch capabilities to accurately simulate the target device.

    1. Why Use Custom Mobile Viewports?

    • Some new or less common mobile devices may not be available in Playwright’s devices list.
    • Custom viewports allow testing on specific screen resolutions and device configurations.
    • They provide flexibility when testing progressive web apps (PWAs) or applications with unique viewport breakpoints.

    2. Example Code for Custom Viewport

    The following Playwright script manually configures a Samsung Galaxy S10 viewport and device properties:

    
    const { test, expect } = require('@playwright/test');
    
    
    test.use({
    
      viewport: { width: 414, height: 896 }, // Samsung Galaxy S10 resolution
    
      userAgent: 'Mozilla/5.0 (Linux; Android 10; SM-G973F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Mobile Safari/537.36',
    
      isMobile: true, // Enables mobile-specific behaviors
    
      hasTouch: true  // Simulates touch screen interactions
    
    });
    
    
    test('Open page with custom mobile resolution', async ({ page }) => {
    
        // Navigate to the target webpage
    
        await page.goto('https://playwright.dev/');
    
    
        // Simulate real-world waiting behavior
    
        await page.waitForTimeout(2000);
    
    
        // Capture a screenshot of the webpage
    
        await page.screenshot({ path: 'android_custom.png' });
    
    
        // Validate that the page title is correct
    
        await expect(page).toHaveTitle("Fast and reliable end-to-end testing for modern web apps | Playwright");
    
    });
    
    

    3. How This Script Works

    • viewport: { width: 414, height: 896 } → Sets the screen size to Samsung Galaxy S10 resolution.
    • userAgent: ‘Mozilla/5.0 (Linux; Android 10; SM-G973F)…’ → Spoofs the browser user agent to mimic a real Galaxy S10 browser.
    • isMobile: true → Enables mobile-specific browser behaviors, such as dynamic viewport adjustments.
    • hasTouch: true → Simulates a touchscreen, allowing for swipe and tap interactions.
    • The test navigates to Playwright’s website, waits for 2 seconds, takes a screenshot, and verifies the page title.

    4. Running the Test

    To execute this test, save it in a file (e.g., custom-viewport.spec.js) and run:

    
    npx playwright test custom-viewport.spec.js
    
    

    After execution, a screenshot named android_custom.png will be saved in your project folder.

    Playwright Mobile Automation for Seamless Web Testing

    5. Testing Other Custom Viewports

    You can modify the script to test different resolutions by changing the viewport size and user agent.

    Example: Custom iPad Pro 12.9 Viewport

    
    test.use({
    
      viewport: { width: 1024, height: 1366 },
    
      userAgent: 'Mozilla/5.0 (iPad; CPU OS 14_6 like Mac OS X) AppleWebKit/537.36 (KHTML, like Gecko) Version/14.1.1 Mobile/15E148 Safari/537.36',
    
      isMobile: false, // iPads are often treated as desktops
    
      hasTouch: true
    
    });
    
    

    Example: Low-End Android Device (320×480, Old Android Browser)

    
    test.use({
    
      viewport: { width: 320, height: 480 },
    
      userAgent: 'Mozilla/5.0 (Linux; U; Android 4.2.2; en-us; GT-S7562) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
    
      isMobile: true,
    
      hasTouch: true
    
    });
    
    

    Real Device Setup & Execution

    Playwright enables automation testing on real Android devices and emulators using Android Debug Bridge (ADB). This capability allows testers to validate their applications in actual mobile environments, ensuring accurate real-world behavior.

    Unlike Android, Playwright does not currently support real-device testing on iOS due to Apple’s restrictions on third-party browser automation. Safari automation on iOS requires WebDriver-based solutions like Appium or Apple’s XCUITest, as Apple does not provide a direct automation API similar to ADB for Android. However, Playwright’s team is actively working on expanding iOS support through WebKit debugging, but full-fledged real-device automation is still in the early stages.

    Below is a step-by-step guide to setting up and executing Playwright tests on an Android device.

    Preconditions: Setting Up Your Android Device for Testing

    1. Install Android Command-Line Tools

    • Download and install the Android SDK Command-Line Tools from the official Android Developer website.
    • Set up the ANDROID_HOME environment variable and add platform-tools to the system PATH.

    2. Enable USB Debugging on Your Android Device

    • Go to Settings > About Phone > Tap “Build Number” 7 times to enable Developer Mode.
    • Open Developer Options and enable USB Debugging.
    • If using a real device, connect it via USB and authorize debugging when prompted.

    3. Ensure ADB is Installed & Working

    Run the following command to verify that ADB (Android Debug Bridge) detects the connected device:

    
    adb devices
    
    
    Running Playwright Tests on a Real Android Device

    Sample Playwright Script for Android Device Automation

    
    const { _android: android } = require('playwright');
    
    const { expect } = require('@playwright/test');
    
    
    (async () => {
    
      // Get the list of connected Android devices
    
      const devices = await android.devices();
    
      if (devices.length === 0) {
    
        console.log("No Android devices found!");
    
        return;
    
      }
    
    
      // Connect to the first available Android device
    
      const device = devices[0];
    
      console.log(`Connected to: ${device.model()} (Serial: ${device.serial()})`);
    
    
      // Launch the Chrome browser on the Android device
    
      const context = await device.launchBrowser();
    
      console.log('Chrome browser launched!');
    
    
      // Open a new browser page
    
      const page = await context.newPage();
    
      console.log('New page opened!');
    
    
      // Navigate to a website
    
      await page.goto('https://webkit.org/');
    
      console.log('Page loaded!');
    
    
      // Print the current URL
    
      console.log(await page.evaluate(() => window.location.href));
    
    
      // Verify if an element is visible
    
      await expect(page.locator("//h1[contains(text(),'engine')]")).toBeVisible();
    
      console.log('Element found!');
    
    
      // Capture a screenshot of the page
    
      await page.screenshot({ path: 'page.png' });
    
      console.log('Screenshot taken!');
    
    
      // Close the browser session
    
      await context.close();
    
    
      // Disconnect from the device
    
      await device.close();
    
    })();
    
    
    
    

    How the Script Works

    • Retrieves connected Android devices using android.devices().
    • Connects to the first available Android device.
    • Launches Chrome on the Android device and opens a new page.
    • Navigates to https://webkit.org/ and verifies that a page element (e.g., h1 containing “engine”) is visible.
    • Takes a screenshot and saves it as page.png.
    • Closes the browser and disconnects from the device.

    Executing the Playwright Android Test

    To run the test, save the script as android-test.js and execute it using:

    
    node android-test.js
    
    

    If the setup is correct, the test will launch Chrome on the Android device, navigate to the webpage, validate elements, and capture a screenshot.

    Screenshot saved from real device

    Playwright Mobile Automation for Seamless Web Testing

    Frequently Asked Questions

    • What browsers does Playwright support for mobile automation?

      Playwright supports Chromium, Firefox, and WebKit, allowing comprehensive mobile web testing across different browsers.

    • Can Playwright test mobile web applications in different network conditions?

      Yes, Playwright allows network throttling to simulate slow connections like 3G, 4G, or offline mode, helping testers verify web application performance under various conditions.

    • Is Playwright the best tool for mobile web automation?

      Playwright is one of the best tools for mobile web testing due to its speed, efficiency, and cross-browser support. However, if you need to test native or hybrid mobile apps, Appium or native testing frameworks are better suited.

    • Does Playwright support real device testing for mobile automation?

      Playwright supports real device testing on Android using ADB, but it does not support native iOS testing due to Apple’s restrictions. For iOS testing, alternative solutions like Appium or XCUITest are required.

    • Does Playwright support mobile geolocation testing?

      Yes, Playwright allows testers to simulate GPS locations to verify how web applications behave based on different geolocations. This is useful for testing location-based services like maps and delivery apps.

    • Can Playwright be integrated with CI/CD pipelines for mobile automation?

      Yes, Playwright supports CI/CD integration with tools like Jenkins, GitHub Actions, GitLab CI, and Azure DevOps, allowing automated mobile web tests to run on every code deployment.

    The post Playwright Mobile Automation for Seamless Web Testing appeared first on Codoid.

    Source: Read More

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleWhy Can’t I Locate Clickable Element in Choose File Keyword?
    Next Article Researchers from Dataocean AI and Tsinghua University Introduces Dolphin: A Multilingual Automatic Speech Recognition ASR Model Optimized for Eastern Languages and Dialects

    Related Posts

    Security

    Nmap 7.96 Launches with Lightning-Fast DNS and 612 Scripts

    May 24, 2025
    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-47535 – Opal Woo Custom Product Variation Path Traversal

    May 24, 2025
    Leave A Reply Cancel Reply

    Hostinger

    Continue Reading

    Windows 11 KB5055523 24H2 adds AI features, direct download links (.msu)

    Operating Systems

    Rilasciato MESA 25.0: Un passo avanti per il gioco su GNU/Linux con supporto a nuove estensioni

    Linux

    Lost and Found Portal Using PHP and MySQL

    Development

    SwDir.dll is Missing or Not Found: 5 Ways to Download it

    Operating Systems

    Highlights

    Design for Colorblind People

    July 7, 2024

    Colorblindness, or color vision deficiency, affects approximately 8% of men and 0.5% of women worldwide.…

    Easily Toggle Ubuntu’s New Wellbeing Reminders On/Off

    May 8, 2025

    Google Wallet now alerts you to loyalty card benefits you’re missing out on

    February 19, 2025

    The best early Amazon Prime Day 2024 deals

    June 26, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.