All challenges · Expert & Verification

Challenge 26 of 29 · Expert authoring · Verification

Device Emulation

Switch a page to a phone-sized viewport so its mobile layout appears. The hidden check confirms what changes at that size.

Skills you will practise

  • viewport size
  • responsive layouts
  • mobile views

The concept

Responsive pages change at different widths: a navigation bar collapses into a menu button, columns stack, some elements hide. To test the mobile layout, the browser needs a mobile-sized viewport.

There are two common ways. page.setViewportSize({ width, height }) resizes the current page, which is quick and works mid-test. In a Playwright Test project, test.use({ ...devices['iPhone 13'] }) (with devices imported from @playwright/test) emulates a whole device: viewport, device scale factor, user agent and touch support.

Viewport width alone triggers CSS media queries. If the page checks for touch or the user agent, you need the full device preset.

The fragile version

Fragile
await page.goto('/');
await expect(page.getByRole('button', { name: 'Menu' })).toBeVisible();

Why it breaks: On the default 1280x720 viewport the desktop layout shows and the mobile menu button is hidden, so the test fails, or passes only on whichever machine happens to be narrow.

A robust Playwright version

Robust
await page.setViewportSize({ width: 375, height: 667 });
await page.goto('/');
await expect(page.getByRole('button', { name: 'Menu' })).toBeVisible();
await expect(page.getByRole('navigation').getByRole('link', { name: 'Pricing' }))
  .toBeHidden();

The viewport is set explicitly, and the test asserts both what appears and what disappears at that size.

This is a general example on a made-up page, not the challenge’s reference solution.

Common mistakes

  • Assuming the default viewport is mobile or desktop without setting it.
  • Expecting setViewportSize to change the user agent or enable touch.
  • Only checking the new element, not that the desktop element hid.

FAQ

What is Playwright's default viewport?

1280x720 unless you configure another one.

How do I emulate an iPhone in Playwright?

Use devices['iPhone 13'] (or another preset) in your config or test.use.

Does setViewportSize emulate touch?

No. It only changes the size; use a device preset or hasTouch for touch.

Try it

Practise this in Challenge 26. You write the code in the browser editor with no setup. It runs in a fresh Chromium, a hidden validator checks what actually happened, and you get pass or fail, the logs and a video of the run. Create a free account to open the practice page and its hints. The reference solution and the hidden validator are shown only after you pass. We never publish solutions here.

Practise this challenge free