QA Graphic

Adding Mobile Emulation to Your Pytest Test

Easily Add Mobile Testing to Your Test Suite

Learn how to simulate a mobile environment in your automated tests using Pytest and Chrome's mobile emulation features.

Why Use Mobile Emulation?

Testing how your website behaves on mobile devices is essential. Rather than using a physical device or a mobile browser emulator, Chrome allows you to simulate mobile conditions directly through WebDriver using mobileEmulation settings.

Setting Up Mobile Emulation in Pytest

To demonstrate mobile emulation in Pytest, you'll need the following packages:

  • pytest
  • selenium
  • chromedriver installed and in your system path

Here's a simple example that simulates a Nexus 5 device while accessing a webpage:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def test_uncloying_new():
    domain = "http://www.cryan.com"
    mobile_emulation = {
        "deviceMetrics": {"width": 360, "height": 640, "pixelRatio": 3.0},
        "userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) "
                     "AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 "
                     "Mobile Safari/535.19",
        "clientHints": {"platform": "Android", "mobile": True}
    }
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
    driver = webdriver.Chrome(options=chrome_options)
    driver.get(domain)
    assert "Welcome" in driver.page_source
    driver.quit()

What's Happening Here?

  • deviceMetrics: Simulates screen dimensions and pixel density.
  • userAgent: Overrides the default user agent to a mobile one.
  • clientHints: Helps simulate how modern mobile browsers send platform data.
  • Chrome Options: Sets up a headless browser with mobile emulation enabled.

Benefits of Mobile Emulation in Tests

  • No need for actual devices or external tools.
  • Fast, scriptable, and easy to integrate into CI/CD pipelines.
  • Improves confidence that your site works across form factors.

 

Comments

Add Your Comments

Name:
Comment:

 

About

Welcome to Pytest Tips and Tricks, your go-to resource for mastering the art of testing with Pytest! Whether you're a seasoned developer or just dipping your toes into the world of Python testing, this blog is designed to help you unlock the full potential of Pytest - one of the most powerful and flexible testing frameworks out there. Here, I'll share a treasure trove of practical insights, clever techniques, and time-saving shortcuts that I've gathered from years of writing tests and debugging code.

Schedule

Thursday 17 PlayWright
Friday 18 Macintosh
Saturday 19 Internet Tools
Sunday 20 Misc
Monday 21 Media
Tuesday 22 QA
Wednesday 23 Veed