A mobile screenshot looks fine. Then someone tries to approve a form at 320px and discovers that its button has vanished. On another page, a long status message is cut off while everything else stays neatly inside the viewport.
A screenshot comparison may detect the difference, but only if the changed pixels are visible, the correct state was captured, and the baseline was reviewed. It does not tell you whether a required action still works.
Responsive testing needs a behavior contract alongside visual regression. For a page with a navigation menu, an approval button, important copy, and a wide data table, that contract might be:
- The document itself does not overflow horizontally.
- The approval action remains visible, enabled, reachable, and capable of completing the expected state change.
- The essential message is not clipped.
- The navigation can be opened and closed with a keyboard, and its focus behavior is predictable.
- The table may scroll inside its own container without forcing the entire page sideways.
The example test fixture uses five viewport widths and five intentionally broken variants. It is a synthetic exercise, not a claim about a production website.
First, decide what must survive the breakpoint
Not everything should be visible in the same state at every width. A desktop navigation row may become a collapsed menu on mobile. A data table can legitimately scroll horizontally inside a bounded region. A secondary card may move below the main content.
Write down the critical content and interaction contract for the page before selecting assertions:
| Risk | Observable contract | Failure example |
|---|---|---|
| Page-wide overflow | Document scroll width does not exceed its viewport width | Fixed-width child creates an 80px horizontal scroll |
| Missing action | Required approval button is visible and usable | Media query hides the only submit button |
| Text clipping | An essential message is readable in full | white-space: nowrap; overflow: hidden cuts a sentence |
| Keyboard regression | Tab reaches the menu, Enter opens it, Escape closes it | Trigger is removed from the tab sequence |
| Inert action | Keyboard activation updates the status and disables the completed action | Button looks enabled but never completes approval |
| Intended local scroll | Wide data is contained by its own scroller | The table pushes the page beyond the viewport |
The distinction matters for accessibility. WCAG 2.2 Understanding Reflow discusses a 320 CSS-pixel equivalent width for vertically scrolling content, while allowing exceptions for content whose two-dimensional layout is essential, including data tables. That is not a rule that every descendant's scrollWidth must equal its clientWidth.
Likewise, a hidden mobile menu is not inherently broken; a missing only route to an action is. Tests should encode the expected behavior, not assume that every element must always be visible.
Set up a reproducible five-width test
The fixture is deliberately small: fixture/index.html contains a responsive two-column layout, a menu button and controlled menu, a primary action, a critical sentence, and a wide table inside overflow-x: auto.
Its Playwright Test suite checks widths of 320, 375, 768, 1024, and 1440 CSS pixels, all at 800px height. These are selected regression samples, not a complete device matrix.
With the fixture's package.json, fixture/index.html, and tests/responsive.spec.js in place, run:
npm install
npx playwright install chromium
npm test
The standalone project declares @playwright/test and reads the HTML fixture via page.setContent(); it does not depend on a development server. In an application, replace setContent with goto('/your-route'), configure baseURL, and select the real controls that users need.
The core structure is:
const { test, expect } = require('@playwright/test');
const widths = [320, 375, 768, 1024, 1440];
for (const width of widths) {
test(`responsive contract at ${width}px`, async ({ page }) => {
await page.setViewportSize({ width, height: 800 });
await page.goto('/review'); // Your application route.
// The document should not require horizontal scrolling.
await expect.poll(() => page.evaluate(() =>
document.documentElement.scrollWidth -
document.documentElement.clientWidth
)).toBeLessThanOrEqual(1);
const approve = page.getByRole('button', { name: 'Approve review' });
await expect(approve).toBeVisible();
await expect(approve).toBeEnabled();
await approve.scrollIntoViewIfNeeded();
await expect(approve).toBeInViewport({ ratio: 1 });
});
}
This is a page-specific example, not a generic scanner: /review and its button must exist in your app. The companion suite contains the corresponding runnable fixture selectors.
Playwright's viewport emulation changes the viewport used for layout. It does not automatically reproduce pinch-zoom behavior, every mobile browser's UI, or the effects of a particular on-screen keyboard. Use device projects and real-device checks where those differences matter.
Why both visibility and viewport assertions?
Playwright's locator assertions automatically retry several conditions, including toBeVisible() and toBeInViewport(). Visibility says the element is displayed; it does not, by itself, express the product requirement that a user can see it within the viewport.
We intentionally scroll the required button into view, then require full viewport intersection. That makes this a test for reachable content, not a requirement that a button below the fold be visible without scrolling. For sticky headers, overlays, or disabled buttons, add tests of the actual action and focus coverage. A successful toBeInViewport() check alone does not prove that an overlay will let the user click.
If your page includes an intentionally wide spreadsheet, measure document-wide overflow separately from the spreadsheet's internal overflow:
const table = page.getByTestId('table-scroll');
await expect(table).toBeVisible();
expect(await table.evaluate(el =>
el.scrollWidth > el.clientWidth
)).toBe(true); // Expected for this fixture at 320px.
Applying a blanket overflow-x: hidden to body may conceal an inaccessible offscreen control without fixing it. It is not a substitute for diagnosing the overflowing child.
Catch a clipped message that does not widen the page
Text can disappear without creating a page scrollbar. Consider an essential order status rendered with white-space: nowrap and overflow: hidden. The document may still have no horizontal overflow while the sentence is unreadable.
For known critical text, compare its content dimensions against its available box:
const clipped = await page.getByTestId('critical-copy').evaluate(el =>
el.scrollWidth > el.clientWidth + 1 ||
el.scrollHeight > el.clientHeight + 1
);
expect(clipped).toBe(false);
The one-pixel tolerance avoids failing on fractional layout rounding. This detects the fixture's deliberately clipped message; it does not prove that arbitrary text is visually intact. Transforms, overlapping siblings, pseudo-elements, gradients, masks, canvas, and intentional ellipsis need different checks. A line-clamp can be a deliberate design requirement for a preview, but must not silently discard text needed to complete a task.
For critical copy, test the meaningful content itself: expect the full sentence in the DOM, check the clipping contract on its container, and review it visually. Do not turn the measurement into a universal rule for every paragraph in your application.
The mobile menu must work without a mouse
The fixture's menu starts collapsed. Hiding its links is expected until the user expands it. The useful keyboard sequence is: Tab reaches the menu button, Enter opens it, Tab reaches the first link, and Escape closes the menu and returns focus to the trigger.
await page.keyboard.press('Tab');
const menu = page.getByTestId('menu-toggle');
await expect(menu).toBeFocused();
await page.keyboard.press('Enter');
await expect(menu).toHaveAttribute('aria-expanded', 'true');
await expect(page.getByTestId('menu-link')).toBeVisible();
await page.keyboard.press('Tab');
await expect(page.getByTestId('menu-link')).toBeFocused();
await page.keyboard.press('Escape');
await expect(menu).toHaveAttribute('aria-expanded', 'false');
await expect(menu).toBeFocused();
This sequence is correct for the supplied fixture, whose menu has a specific tab order and implements Escape behavior. A production disclosure menu may use a different valid focus model; make the assertion match its documented interaction design. Do not force focus movement purely to appease the test.
The suite also tabs to Approve review and activates it with Enter. It then asserts that the status changes to Approved and the completed button becomes disabled. The fifth negative control leaves the button visible but deliberately prevents this state change. A layout that looks correct but cannot complete the required task should fail the responsive contract.
A keyboard test can still miss focus obscured by a sticky overlay, lost focus after navigation, inaccessible names, or an unusable screen-reader experience. WCAG 2.2 Focus Not Obscured addresses one aspect; a visible focus indicator and manual checks still matter. For a deeper focus-management example, see the accessible modal focus guide.
Prove the checks can fail
A suite that passes on a clean demo proves less than a suite whose assertions also detect controlled defects.
The fixture accepts five test-only changes, injected at 320px:
overflow: a narrow-screen element expands the page by 80px.hidden: a media query hides the required approval button.clipped: the critical message is forced into a 120px non-wrapping box.keyboard: the menu trigger receivestabindex="-1"and is skipped by Tab.inert: the approval button remains visible but silently fails to update its status.
The accompanying tests assert that the corresponding detector trips for each deliberately broken case. The defect injection is isolated to a synthetic page; these changes should never be deployed to an application.
This practice is a small form of negative-control testing. It is especially useful when someone proposes simplifying the suite to a screenshot-only assertion or suppressing every overflow warning.
Keep screenshots, but use them for the right questions
Visual regression still helps. It catches changes to spacing, wrapping, typography, alignment and composition that no short list of semantic assertions can cover.
For a stable element or page, Playwright provides toHaveScreenshot():
await expect(page).toHaveScreenshot('review-375.png', {
animations: 'disabled',
});
Generate and review the reference snapshot deliberately. Do not automatically accept a new baseline simply to make a regression pass. The Playwright visual comparisons guide warns that OS, browser version, rendering configuration, fonts and hardware differences can affect pixel output. Keep the baseline environment consistent and record why a changed snapshot is accepted.
A practical split:
- Behavior assertions: required button, full critical copy, keyboard opening/closing, expected state changes.
- Layout measurements: unwanted page scroll, known clipped containers, important content outside its allowed region.
- Visual snapshots: broad composition changes, unexpected wrapping, overlays, alignment.
- Manual accessibility checks: zoom/reflow, keyboard exploration, screen-reader feedback, focus visibility, touch targets.
A test that passes screenshots is not proof of WCAG compliance. For accessible automation limitations, see the accessibility testing in CI/CD guide. For container-dependent layouts, the CSS container queries guide explains why a wide viewport can still hold a very narrow component.
What the test results show
The synthetic fixture was checked in headless Chromium. The matching JavaScript Playwright Test suite was also executed locally:
| Check | Observed result |
|---|---|
| Normal layout at 320, 375, 768, 1024, 1440px | 5/5 passed |
| Injected page overflow, hidden action, clipped text, keyboard exclusion and inert action | 5/5 defects detected |
JavaScript suite and Playwright config syntax (node --check) | Passed |
JavaScript @playwright/test suite | 10/10 passed in a local Windows/Chromium run |
| Firefox, WebKit, screenshots, zoom, real mobile devices, screen reader | Not tested |
The Node Playwright Test run passed 10 tests: five viewport checks and five fault-injection checks. A separate Chromium browser run also exercised the HTML fixture. These results verify the stated behavior in the synthetic example, not on a production website or across every browser. No visual snapshot baseline was executed, and neither run demonstrates WCAG conformance.
When you adapt this package to a real product, run it in CI with a stable browser version and dedicated test data. A failure should say which viewport, element and user contract broke—not only that one picture differs from another. If a test fails only in CI, the Playwright local-versus-CI debugging guide covers timing, data isolation and environment differences.
Primary references
- Playwright: Emulation — viewport and device configuration.
- Playwright: Assertions — auto-retrying visibility and viewport assertions.
- Playwright: Actionability — what actions do and do not wait for.
- Playwright: Visual comparisons — snapshot baselines and rendering variability.
- Playwright: Accessibility testing — automated scanning limitations.
- W3C: WCAG 2.2 Understanding Reflow — 320px equivalent reflow requirement and meaningful exceptions.
- W3C: WCAG 2.2 Focus Not Obscured (Minimum) — focused controls must not be entirely hidden by author-created content.
The code examples are scoped to a minimal responsive fixture. Passing them does not establish any production site's accessibility or responsive quality.
