Web Testing
Cross-browser Testing Techniques
This course teaches the practice of verifying that a web application looks and behaves correctly across the different browsers and rendering engines your users actually use. You will learn why browsers disagree on the same HTML, CSS and JavaScript, how to build a sane browser and device test matrix, how to automate checks with tools like Playwright and Selenium, how to catch layout and interaction bugs before release, and how to wire cross-browser checks into a continuous integration pipeline. The course mixes conceptual explanation with hands-on code examples, practical exercises and a quiz, so that by the end you can design and run a cross-browser testing strategy for a real project rather than just reacting to bug reports from confused users on an unfamiliar browser.
Intermediate · By the Xtest team · About 34 minutes to read
Introduction
Every browser is built on a rendering engine that parses HTML, applies CSS and runs JavaScript in its own way. Chromium-based browsers use Blink, Firefox uses Gecko, and Safari uses WebKit. Even when two browsers both claim to support a CSS property or a JavaScript API, small differences in defaults, timing, and edge-case behavior mean the same page can look or act differently depending on where it is opened. Add mobile browsers, different screen sizes, pixel densities, and assistive technologies into the mix, and the surface area for bugs grows quickly. Cross-browser testing is the discipline of finding and preventing these differences before they reach users.
This course starts from first principles: what actually differs between browsers, and why. It then moves into building a practical testing strategy, including how to choose which browsers and devices matter for your audience, how to write automated tests that run against multiple browser engines, how to catch visual and responsive layout issues, and how to fold all of this into a continuous integration pipeline so that regressions are caught automatically rather than reported by frustrated users. Along the way you will see real code using widely used public tools such as Playwright and Selenium, work through two hands-on exercises, and test your understanding with a quiz. By the end of the course you should be able to design a cross-browser test plan for a real project, automate the repetitive parts of it, and know where manual exploration is still the right call.
Understanding Cross-Browser Compatibility Challenges
Before you can test across browsers effectively, you need to understand what actually varies between them and why. A browser is not a single monolithic thing: it is made of a rendering engine (which parses HTML and CSS and paints pixels), a JavaScript engine (which executes your scripts), and a set of built-in APIs (storage, forms, media, networking). Each of the major engine families, Blink, Gecko and WebKit, has its own implementation of these pieces, maintained separately and shipping on its own schedule. That means a CSS property can be supported in one engine and not another, supported but with a different default value, or supported with a different interpretation of an edge case such as how flexbox gaps or sticky positioning behave near scroll boundaries.
The same is true for JavaScript. Most modern browsers agree on the core language, but newer Web APIs (new form input types, newer storage or media APIs, newer CSS features exposed to JavaScript) can lag behind in some engines, or behave slightly differently when an edge case is hit, such as the order of events fired during a drag-and-drop interaction or a file upload.
A second source of real-world differences is not the engine itself but the platform around it: a desktop browser and the same browser's mobile version often expose different viewport sizes, touch versus mouse input, different default font rendering, and different handling of elements like date pickers or select dropdowns, which are frequently drawn by the operating system rather than the page itself. Screen pixel density (standard versus high-density displays) can also expose rounding differences in layout that only show up on certain devices.
A practical cross-browser strategy does not try to test every possible browser and device combination; that list is effectively infinite. Instead it is built around three questions: which browsers does your actual or intended audience use, which features of your application are most likely to expose engine differences (complex CSS layout, custom form controls, canvas or media, drag-and-drop, animations), and which of those differences are worth fixing versus accepting. Feature detection, rather than browser sniffing by name or version string, is the standard way to make code adapt safely: you check whether a specific API or CSS property is supported and provide a fallback, instead of guessing based on which browser is calling.
This section lays the groundwork: the vocabulary of rendering engines, the categories of bugs you should expect, and the mental model of 'engine differences plus platform differences plus density differences' that you will use for the rest of the course when you design test matrices and automated checks.
Rendering Engines and Their Quirks
Blink (used by Chromium-based browsers), Gecko (used by Firefox) and WebKit (used by Safari) each parse CSS and lay out pages independently, following the same published web standards but not always on the same timeline or with identical edge-case behavior. A CSS feature can land in one engine months or years before another, and even once all three support a feature, subtle differences remain: how a flex container distributes leftover space, how a sticky-positioned element behaves when its container also scrolls, how text wraps inside a constrained grid cell, or how a transform interacts with a filter applied to the same element.
Form controls are a classic source of visible differences because many of them, such as date pickers, color pickers, range sliders and multi-select dropdowns, are drawn by the operating system or the browser's own UI rather than styled purely with your CSS. That means the exact same markup can look completely different across engines and platforms, and your CSS may only be able to influence it partially.
JavaScript timing is another quiet source of bugs: the order in which certain events fire (for example during drag-and-drop, or around focus and blur on custom inputs), and how asynchronous APIs resolve relative to rendering, can differ slightly between engines. These differences rarely show up in simple pages but become visible in interactive, animation-heavy or form-heavy applications, which is exactly where cross-browser testing earns its keep.
Understanding which category a potential bug falls into, a CSS layout quirk, a form-control rendering difference, or a JavaScript timing issue, helps you decide the right tool to catch it: automated layout assertions, a close visual look, or a step-through of the interaction itself.
Common Sources of Cross-Browser Bugs
Most cross-browser bugs fall into a handful of recurring categories. CSS layout bugs come from flexbox and grid edge cases, from units that round differently at high pixel density, and from vendor-prefixed or newly-shipped properties that are not supported everywhere yet. JavaScript API bugs come from newer browser APIs, storage quotas that differ by browser, or from code that assumes a particular event order. Font and text rendering differences come from how each engine measures and wraps text, which can shift layout by a few pixels and cascade into overlapping elements. Viewport and input differences come from mobile browsers exposing touch events and different default zoom or scroll behavior compared to desktop.
A practical way to reduce these bugs before they ever reach a tester is to rely on feature detection in your own code: checking 'IntersectionObserver' in window or using a CSS @supports query before depending on a feature, and providing a reasonable fallback when it is missing, rather than assuming every browser your users might have supports everything the newest one does. This does not replace testing, but it shrinks the number of surprises that testing needs to catch, and it turns an unpredictable crash or silent failure into a predictable, intentional fallback that you can then verify with a normal functional test.
// playwright.config.js
// Run the same test suite against three different browser engines
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
],
});
A Playwright configuration that runs every test in the suite three times, once against each major rendering engine (Blink via Chromium, Gecko via Firefox, WebKit via Safari's engine), so a single command gives you cross-engine coverage.
// Feature detection instead of browser sniffing
function supportsIntersectionObserver() {
return 'IntersectionObserver' in window;
}
if (supportsIntersectionObserver()) {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
}
});
});
document.querySelectorAll('.lazy-section').forEach((el) => observer.observe(el));
} else {
// Fallback: show everything immediately rather than relying on the API
document.querySelectorAll('.lazy-section').forEach((el) => el.classList.add('visible'));
}
Checking for a specific API before using it, with a safe fallback, is more reliable across browsers than checking the browser's name or version string.
/* Use @supports to apply modern CSS only where it is actually supported */
.card-grid {
display: flex;
flex-wrap: wrap;
}
@supports (display: grid) {
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}
}
A CSS feature query gives engines that support grid a grid layout, while older or more limited engines keep a flexbox-based fallback, so the page stays usable everywhere.
Tips
- Build your test matrix around your actual or intended audience's browsers first, not every browser that exists.
- Prefer feature detection (checking for an API or CSS property) over sniffing a browser's name or version string.
- Pay special attention to form controls, drag-and-drop, animations and canvas or media elements, since these are the most common places rendering engines disagree.
- Test at more than one pixel density when layout precision matters, since rounding differences are more visible on high-density displays.
Common pitfalls
- Assuming that 'WebKit' and 'Safari' always behave identically: testing against a generic WebKit build is a reasonable proxy but is not a perfect substitute for checking the real browser on the real operating system when a bug is suspected there.
- Testing only the newest version of each browser: some audiences stay on older versions longer than expected, so decide deliberately how far back your matrix needs to go rather than defaulting to 'latest only'.
- Relying on browser or user-agent string checks in application code: user agents can be spoofed or missing entirely, and they tell you nothing about whether a specific feature is actually supported.
Building a Cross-Browser Test Strategy and Matrix
A cross-browser test matrix is the master plan that tells your team exactly which browser, version, operating system, and screen size combinations get tested, and how. Without a matrix, teams either waste time testing combinations nobody uses or discover gaps only when a customer reports a broken checkout page on an old Android browser. Building a good matrix starts with data, not guesswork: pull your own analytics to see which browsers and devices your real users actually run, then rank combinations by traffic share and business value rather than trying to cover every possible pairing of browser, OS, and resolution, which grows combinatorially and quickly becomes untestable.
Once you know which combinations matter, split your coverage into two tiers. Tier one is your critical path: sign-up, login, checkout, and any flow tied directly to revenue or compliance. These get tested on every supported browser and device on every release. Tier two is everything else: secondary flows and edge-case settings pages get a lighter touch, often just the top two or three browsers, run less frequently or only before a major release.
Automation handles repeatable regression checks across the matrix efficiently, but it cannot replace human judgment entirely. Reserve manual exploratory passes on real devices for new features, visually complex pages, and anything involving touch gestures, since automated scripts are good at clicking the same button the same way every time but weak at noticing that a layout looks subtly wrong. Document the matrix itself, in a shared wiki page or spreadsheet, so product managers, developers, and support staff all know what 'tested' means and can push back if a customer's device falls outside current coverage.
Risk-Based Prioritization
Risk-based prioritization means spending your limited testing time where failure would hurt the most, rather than spreading it evenly across every browser and device. Start by scoring each user flow on two axes: how many users take that path, and how costly a failure would be if it broke. A checkout flow used by thousands of customers daily scores high on both axes and belongs in your top tier of coverage. An admin settings page used by three internal staff scores low on both and can be checked occasionally by hand.
Apply the same thinking to browser and device selection. If your analytics show that a particular older browser version accounts for a small and shrinking slice of traffic, it is reasonable to drop it from automated regression and instead spot-check it before major releases. Conversely, if a flow involves payment or legally required disclosures, test it on every supported combination even if the traffic share for some of those combinations is modest, because the cost of a failure there is disproportionately high.
Revisit the scoring regularly. Browser usage shifts, new devices appear, and a flow that used to be low-risk can become high-risk after a redesign or a new regulatory requirement. Treat the matrix as a living document with an owner who updates it each quarter, not a one-time deliverable that gets stale within months. Pair this review with a short retrospective on any production bug that slipped through, asking whether the matrix should have caught it and adjusting accordingly.
Documenting and Communicating the Matrix
A test matrix that lives only in one engineer's head is not a strategy, it is a liability. Write the matrix down in a format the whole team can read: a spreadsheet or wiki table with rows for user flows and columns for browser and device combinations, each cell marked as automated, manual, or not covered. Include a short note on cadence, for example whether a cell is checked on every pull request, nightly, or only before a release.
Make the 'not covered' cells as visible as the covered ones. Teams often document what they test but stay silent about what they deliberately skip, which means a support engineer has no way to know whether a reported bug falls inside or outside current coverage. A clearly marked gap lets someone make an informed call about whether to file a one-off manual check rather than assuming the automation would have caught it.
Tie the matrix to your release process by linking it from your release checklist or CI pipeline documentation, so it is the first thing a new team member finds when asking what gets tested before a deploy. Review the document in sprint planning or release retrospectives, and update it the same day you add or drop a browser from the automated suite, since a matrix that lags behind the actual test code quickly loses the team's trust and stops being consulted.
// playwright.config.js
module.exports = {
projects: [
{ name: 'chromium-desktop', use: { browserName: 'chromium', viewport: { width: 1280, height: 800 } } },
{ name: 'firefox-desktop', use: { browserName: 'firefox', viewport: { width: 1280, height: 800 } } },
{ name: 'webkit-desktop', use: { browserName: 'webkit', viewport: { width: 1280, height: 800 } } },
{ name: 'chromium-mobile', use: { browserName: 'chromium', viewport: { width: 390, height: 844 } } },
],
};
A Playwright config that defines the top tier of a test matrix: Chromium, Firefox and WebKit at desktop size, plus a mobile viewport on Chromium. Running `npx playwright test` executes every spec against each project, giving automated coverage of the critical browser combinations in one command.
// critical-flow.spec.js
const { test, expect } = require('@playwright/test');
test('checkout completes across configured browsers', async ({ page }) => {
await page.goto('https://example.com/cart');
await page.click('text=Checkout');
await page.fill('#card-number', '4242424242424242');
await page.click('text=Pay now');
await expect(page.locator('text=Order confirmed')).toBeVisible();
});
A single checkout spec that, combined with the multi-project config above, runs automatically against every browser and viewport in the critical-path tier, so a regression in any one of them fails the build.
Tips
- Pull real browser and device usage data from your own analytics before building the matrix, rather than guessing which combinations matter.
- Keep the matrix in a shared, easy-to-find document and update it the same day coverage changes, so it never drifts out of sync with the actual test suite.
- Reserve manual exploratory testing for new features and visually complex pages, since scripted checks are reliable for repeatable flows but weak at spotting subtle layout problems.
Common pitfalls
- Trying to cover every possible browser, OS and screen size combination: the matrix becomes too large to maintain and most of it tests paths almost no user takes. Rank combinations by real traffic and business risk instead.
- Leaving gaps in coverage undocumented: when nobody writes down what is deliberately not tested, a reported bug on an uncovered combination looks like a test escape instead of an accepted risk. Mark every gap explicitly in the matrix.
Automating Cross-Browser Checks with Playwright and Selenium
Writing one test suite that runs cleanly against multiple browser engines is less about clever tricks and more about discipline: keep the test logic engine-agnostic and push every engine-specific detail (waits, selectors, driver setup) into a thin layer the test never touches directly. Both Playwright and Selenium support this model, but they get you there differently. Playwright ships with Chromium, Firefox and WebKit builds out of the box and a config file that turns "run on three browsers" into a list of projects rather than a rewrite. Selenium relies on WebDriver, so you manage a driver binary (or a Grid) per browser and the API surface is a little lower level, which means your own abstraction layer carries more weight.
The practical goal is a test that reads like a user story (go to login, enter credentials, submit, assert dashboard) with zero if (browser === 'firefox') branches inside it. You get there with page objects, a shared set of wait helpers, and locators chosen for stability rather than convenience. A locator that only works in Chromium's DOM quirks will quietly break your Firefox or WebKit run, so prefer accessible roles, labels and test ids over brittle CSS paths that happen to work today.
Running the grid in parallel is the other half of the job. Playwright's built-in projects give you per-browser parallelism for free from a single config; Selenium Grid lets you fan the same WebDriver script out across nodes running different browsers and versions. Either way, the win only shows up if your suite is actually engine-agnostic, so build that discipline first and parallelize second.
Structuring Page Objects for Engine-Agnostic Logic
A page object should describe what a page lets a user do, not how any particular browser renders it. Keep three layers separate: the test (what should happen), the page object (how to find and interact with elements), and the runner config (which browser engine executes it). The page object's methods (login(user, pass), submitOrder()) stay identical across engines; only the locators inside them should ever need per-engine tuning, and ideally never.
Favour locators built on semantics: getByRole, getByLabel, getByTestId in Playwright, or By.cssSelector built around data-testid attributes in Selenium. These survive layout differences between Chromium, Firefox and WebKit far better than deeply nested CSS paths, which often differ subtly across rendering engines because of how each one computes shadow DOM or pseudo-elements.
Waits deserve their own small utility module. Playwright auto-waits for actionability before most actions, which removes a whole class of flake, but assertions on dynamic content still benefit from explicit expect(locator).toBeVisible() style waits with a sensible timeout. Selenium has no built-in auto-wait, so every interaction needs an explicit WebDriverWait with an expected_condition; skipping this is the single most common source of cross-browser flakiness, because browsers differ in how fast they paint and settle. Centralising these waits in one helper means a timing fix for Firefox doesn't have to be copy-pasted into forty test files.
Running the Grid: Parallel Browsers in Playwright and Selenium
Playwright's config file defines "projects", each pointing at a browser engine (chromium, firefox, webkit) with its own options; running npx playwright test executes the whole suite against every project in parallel by default, with separate traces and reports per engine. This is the fastest path to a real cross-browser matrix because there is no separate grid infrastructure to stand up.
Selenium's equivalent is Selenium Grid: a hub (or, in modern versions, a router) that distributes WebDriver sessions to nodes, each node offering one or more browser versions. You point your test's RemoteWebDriver at the grid's URL with desired_capabilities describing the browser you want, and the grid schedules the session onto a matching node. This scales well when you need specific browser and OS combinations a single machine cannot host, but it adds operational overhead: nodes to provision, driver versions to keep in sync with browser versions, and session queuing to watch when demand outstrips node capacity.
Whichever tool you use, keep parallel runs independent: no shared test data, no shared login session, no writes to the same database row from two engines at once. Flaky cross-browser failures are often not engine bugs at all but two parallel workers tripping over shared state. Tag slow or flaky specs so they can be retried or quarantined without blocking the whole matrix, and keep each engine's report separate so a WebKit-only failure doesn't get lost in a wall of green Chromium results.
// playwright.config.js
const { defineConfig, devices } = require('@playwright/test');
module.exports = defineConfig({
testDir: './tests',
fullyParallel: true,
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
],
});
// tests/login.spec.js
const { test, expect } = require('@playwright/test');
test('user can log in', async ({ page }) => {
await page.goto('https://example.com/login');
await page.getByLabel('Username').fill('demo_user');
await page.getByLabel('Password').fill('demo_pass');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
});
A single Playwright spec runs unmodified against Chromium, Firefox and WebKit because the config defines three projects; `getByLabel` and `getByRole` locators keep the test stable across engines without any browser-specific branching.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def make_driver(browser_name, grid_url):
options = {
'chrome': webdriver.ChromeOptions(),
'firefox': webdriver.FirefoxOptions(),
}[browser_name]
return webdriver.Remote(command_executor=grid_url, options=options)
def test_login(browser_name, grid_url='http://localhost:4444/wd/hub'):
driver = make_driver(browser_name, grid_url)
try:
driver.get('https://example.com/login')
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.ID, 'username'))).send_keys('demo_user')
driver.find_element(By.ID, 'password').send_keys('demo_pass')
driver.find_element(By.CSS_SELECTOR, '[data-testid="submit"]').click()
wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'h1')))
finally:
driver.quit()
A Selenium Grid test requests a remote session for a given browser name, with explicit `WebDriverWait` calls standing in for Playwright's automatic waits since Selenium does not wait for actionability on its own.
Tips
- Centralise waits and locators in one shared module so a timing fix for one browser engine does not need to be copy-pasted across every test file.
- Prefer role, label and test-id based locators over CSS paths; they survive the small DOM differences between Chromium, Firefox and WebKit far better.
- Keep parallel workers free of shared state (no shared login session, no shared database row) so failures are genuine engine differences rather than race conditions.
Common pitfalls
- Branching test logic with `if (browser === 'firefox')` instead of pushing the difference into the page object or a wait helper; this quietly turns one suite into three suites to maintain.
- Forgetting that Selenium has no built-in auto-wait: interactions fired the instant the script reaches them will pass in a fast local Chrome run and fail intermittently in Grid runs against slower nodes, so every action needs an explicit `WebDriverWait`.
Catching Visual and Responsive Layout Differences
Layout regressions are some of the sneakiest cross-browser bugs: the page loads, no error is thrown, but a button sits behind another element, a sidebar overlaps the main content, or text wraps where it shouldn't. Catching these issues reliably across browsers and viewport sizes takes more than eyeballing a page once in Chrome. This section covers three complementary approaches: manual review checklists for human testers, structured exploratory passes that focus attention on known risk areas, and automated functional assertions that check visibility, position, and computed style directly in code. The goal is to catch the layout breaking without relying on brittle pixel-by-pixel image comparison, which tends to produce false positives from anti-aliasing, font rendering, and animation timing differences between browsers and operating systems.
A manual checklist should cover the handful of patterns that break most often: fixed headers overlapping content on scroll, flex or grid containers collapsing when content is longer than expected, modals and dropdowns rendering off-screen on narrow viewports, and text truncation or overflow at different zoom levels. A structured exploratory pass takes that checklist and applies it deliberately: resize the viewport through a set of breakpoints, zoom in and out, and toggle between light and dark themes or right-to-left layouts if the app supports them, watching specifically for the patterns on the list rather than browsing freely.
Automated functional assertions turn those same checks into code. Instead of comparing screenshots pixel by pixel, you query the DOM for an element's bounding box, visibility, and computed style, and assert that the values make sense: a button is fully within the viewport, a sidebar's width is at least a minimum value, two elements don't overlap. These assertions are fast, deterministic, and immune to rendering noise, which makes them far more reliable to run on every build than a visual diffing tool.
Manual Checklists and Exploratory Passes
Before writing a single assertion, it helps to have a short, repeatable checklist that a human tester (or a careful exploratory session) runs through on each browser and breakpoint. A good checklist is specific rather than vague: instead of 'check the layout looks right', list concrete failure patterns such as 'header stays fixed and does not overlap content when scrolling', 'form labels do not wrap onto two lines at 320px width', 'the primary call-to-action button remains visible without horizontal scrolling', and 'tooltips and dropdowns stay within the viewport near the edges of the screen'.
A structured exploratory pass applies this checklist methodically across a matrix of browsers and viewport widths, commonly including a narrow phone width, a tablet width, and a few desktop widths, with and without browser zoom applied. Testers resize the window live and watch for sudden reflows, content jumping, or elements disappearing behind others, taking a screenshot and a short note whenever something looks off. This kind of pass is cheap to run and catches the layout bugs that are hardest to specify in code ahead of time, such as a long user name that breaks a card's layout or a translated string that overflows a button.
The key discipline is writing down what was checked and what passed, not just what failed, so that the same ground isn't covered differently each time and gaps don't go unnoticed. Pairing the checklist with the automated assertions described next means humans focus their judgment on genuinely new or ambiguous layouts, while the computer handles the repetitive, well-defined checks on every single run.
Writing Functional Layout Assertions
Functional layout assertions check the properties that actually matter for usability: is the element visible, is it positioned where it should be, and does its computed style match expectations. These checks use the same browser APIs that power visual judgment, just expressed as code instead of pixels. Three building blocks cover most cases: getBoundingClientRect() for position and size, getComputedStyle() for resolved CSS values like display, visibility, and color, and simple viewport math to confirm an element is fully on-screen.
A typical assertion checks that an element's bounding box falls entirely within the viewport's width and height, that its width is above some sensible minimum so it hasn't collapsed, and that two elements expected to sit side by side don't have overlapping rectangles. Another common check compares a computed style property, such as confirming a navigation menu's display is not none at a given breakpoint, or that a modal's z-index places it above the page content.
The advantage over image-based visual regression is stability: these assertions don't care about sub-pixel font rendering differences between browsers, animation timing, or slightly different anti-aliasing, so they don't need a human to review a pile of false-positive diffs after every run. The trade-off is that they only catch the specific conditions you thought to assert, so pair them with the manual exploratory passes above to cover layouts you haven't anticipated.
const { test, expect } = require('@playwright/test');
test('primary button stays within viewport at mobile width', async ({ page }) => {
await page.setViewportSize({ width: 375, height: 667 });
await page.goto('https://example.com/checkout');
const button = page.locator('[data-testid="submit-order"]');
await expect(button).toBeVisible();
const box = await button.boundingBox();
const viewport = page.viewportSize();
expect(box.x).toBeGreaterThanOrEqual(0);
expect(box.y).toBeGreaterThanOrEqual(0);
expect(box.x + box.width).toBeLessThanOrEqual(viewport.width);
expect(box.y + box.height).toBeLessThanOrEqual(viewport.height);
});
Checks that the checkout button's bounding box falls entirely within a 375x667 mobile viewport, catching cases where the button is pushed off-screen or clipped.
const { test, expect } = require('@playwright/test');
test('nav menu is actually shown at desktop width', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 800 });
await page.goto('https://example.com');
const nav = page.locator('nav.main-menu');
const display = await nav.evaluate(el => getComputedStyle(el).display);
const visibility = await nav.evaluate(el => getComputedStyle(el).visibility);
expect(display).not.toBe('none');
expect(visibility).toBe('visible');
});
Reads the computed style of a navigation element to confirm it is actually rendered at a desktop breakpoint, rather than relying on a screenshot to show the menu is present.
Tips
- Group layout assertions by breakpoint and keep the list of breakpoints the same across all automated tests, so results stay comparable over time.
- Favor relative checks (an element is within the viewport, two elements don't overlap) over hardcoded pixel positions, which break the moment a design tweaks spacing.
- Run exploratory passes right after any CSS framework upgrade or major redesign, since global style changes are the most common source of widespread layout breakage.
Common pitfalls
- Asserting exact pixel coordinates for elements: minor, harmless spacing changes will constantly break the test. Assert ranges and relationships (within viewport, minimum width) instead.
- Only testing one desktop viewport size: most layout bugs appear at the narrow and wide extremes, so a single mid-size window misses the breakpoints where flex and grid layouts actually reflow.
Wiring Cross-Browser Tests into Continuous Integration
A cross-browser suite earns its keep only once it runs automatically, on every pull request, without anyone remembering to click a button. The goal is a pipeline that spins up each target browser, runs the full suite against it, and reports a single clear verdict: did Chromium, Firefox and WebKit all pass, or did one of them regress something the others didn't catch?
The naive approach, running browsers one after another in a single job, works but it is slow: a ten-minute suite becomes thirty minutes once you add two more browsers. The fix is to treat browsers as independent, parallel jobs rather than sequential steps inside one job. Most CI systems support this with a build matrix, where the same job definition is repeated once per matrix value, each running concurrently on its own runner.
Flakiness is the other recurring problem. A test that waits on a fixed timeout instead of a real condition will pass on a fast runner and fail on a loaded one, and it tends to fail differently in each browser because rendering and network timing differ. Rather than ignoring red builds or rerunning the whole pipeline by hand, configure a small number of automatic retries scoped to the test runner, and track which tests retry often so they get fixed rather than silently tolerated.
This section covers wiring the matrix, failing the build correctly when any browser fails, and keeping retries honest instead of a blanket excuse for weak waits.
Parallelizing the Browser Matrix
Define the suite once and let the CI system fan it out across browsers using a matrix. Each matrix entry becomes its own job with its own runner, its own log, and its own pass or fail status, and all of them start at roughly the same time instead of queuing behind each other. This keeps total pipeline time close to the slowest single browser's run time rather than the sum of all three.
For larger suites, combine the browser matrix with sharding: split the test files into two or four groups per browser so that, say, Chromium's share of the suite also runs in parallel across multiple workers. Most test runners that support multiple browsers out of the box, such as Playwright, accept a shard index and a shard count as command-line flags, which maps cleanly onto a second matrix dimension in CI.
Keep each job's artifacts separate and clearly named, usually by including the browser name in the job name and in any uploaded trace or screenshot folder, otherwise a failure from Firefox and a failure from WebKit become indistinguishable in a shared artifact list. Cache dependency installs per browser where the CI system allows it, since reinstalling browser binaries on every run is the single biggest avoidable cost in a cross-browser pipeline.
Failing the Build and Handling Flaky Tests
The build should fail if any browser in the matrix fails, not just the first one checked. Most CI systems do this by default for a matrix, since a matrix job is really N independent jobs and the overall workflow status is the worst of them, but double-check the setting: some configurations have a fail-fast option that cancels the other browsers' jobs the moment one fails, which hides results you probably want to see (did only Firefox fail, or did all three?). Turning fail-fast off costs a little compute but gives a complete picture in one pipeline run.
For flakiness, configure retries at the test runner level, scoped tightly: two retries for an end-to-end test is reasonable, but retries should never be the answer to a test that is wrong on principle, such as one that clicks before an element is interactive. A test that needed a retry should be visible in the CI report as retried, not silently merged into a plain pass, so that a test retrying on every run gets attention before it becomes background noise. Separate transient infrastructure flakiness, such as a shared staging environment briefly returning errors, from genuine timing bugs in the test itself; the first is fixed by hardening the environment, the second by replacing a fixed wait with a wait for a specific condition.
name: cross-browser-tests
on: [pull_request]
jobs:
test:
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npx playwright install --with-deps ${{ matrix.browser }}
- run: npx playwright test --project=${{ matrix.browser }} --retries=2
- uses: actions/upload-artifact@v4
if: failure()
with:
name: trace-${{ matrix.browser }}
path: test-results/
A GitHub Actions workflow that runs a Playwright suite as three parallel matrix jobs, one per browser, with fail-fast disabled so all three report independently and a trace is uploaded only for the browsers that failed.
# Fail the overall pipeline step only if the last command's exit code is non-zero,
# and print a short summary of which browser failed before exiting
npx playwright test --project=$BROWSER --reporter=line --retries=2
STATUS=$?
if [ $STATUS -ne 0 ]; then
echo "Cross-browser suite FAILED on $BROWSER"
exit $STATUS
fi
A shell snippet usable inside any CI job to propagate the test runner's real exit code and clearly label which browser's run failed, useful when a pipeline wraps the test command in extra scripting.
Tips
- Pin exact browser binary versions in CI rather than letting them float, so a failure is caused by your code, not an unannounced browser update.
- Name CI jobs and uploaded artifacts with the browser in the title so a failing pull request check is diagnosable from the job list alone.
- Track retry counts over time per test, not just pass or fail, so a test that always needs its retry gets rewritten before it starts failing outright.
Common pitfalls
- Leaving fail-fast enabled on the matrix: the first browser to fail cancels the others' jobs, so you never learn whether the regression is specific to one engine or affects all three.
- Using retries as a substitute for a proper wait condition: a test that passes on its second attempt because of a fixed sleep is still a bad test, it just fails less often, and it will eventually fail in front of a reviewer at the worst time.
Exercises
Exercise 1: Build a Minimal Multi-Browser Playwright Suite
In this exercise you will take a small public page (or a simple page of your own, such as a login form or a signup form) and write a Playwright test that checks a core user flow, then configure it to run against Chromium, Firefox and WebKit. The goal is not to find a bug, necessarily, but to practice the mechanics of running one test suite across three engines and reading the per-browser results. You will also add one feature-detection-based fallback to a small piece of JavaScript or CSS on a page you control, and verify with your test suite that the fallback actually works in at least one of the three engines where the primary feature might not be supported. This exercise builds the muscle memory for structuring a project so that 'cross-browser' is a configuration choice rather than a separate test suite to maintain.
- Install Playwright and initialize a new test project.
- Write a test that visits your chosen page, fills in a simple form (or performs a core click-through flow), and asserts the expected outcome.
- Add 'chromium', 'firefox' and 'webkit' as projects in your Playwright config, as shown in the section's code example.
- Run the suite with all three projects and record which, if any, fail or behave differently.
- If any test fails on one engine, investigate whether it is a real application bug, a timing issue, or a selector that needs to be more specific, and fix it.
- Add one small feature-detection fallback (CSS @supports or a JavaScript capability check) to the page, and extend your test to assert the fallback path renders correctly.
Expected outcome: A working Playwright test suite that runs the same test logic against three rendering engines, a short written note on any behavior differences you found between engines, and a passing test that specifically exercises your feature-detection fallback.
Exercise 2: Risk-Based Cross-Browser Test Matrix
In this exercise you will design, on paper, a cross-browser test matrix for a hypothetical e-commerce checkout flow. Rather than listing every possible browser and device combination, you will apply risk-based thinking: which browsers and devices matter most for this audience, which parts of the checkout flow (payment form, address autocomplete, promo code field, order confirmation) are most likely to expose engine differences, and which combinations you will deliberately leave out of automated coverage and instead check manually on a periodic basis. You will then map each cell of your matrix to either 'automated' or 'manual exploratory' and justify the choice in one sentence per cell.
- List the browsers and device types you believe matter most for a general e-commerce audience, and briefly justify the list.
- List the distinct steps of the checkout flow (cart review, address entry, payment entry, promo code, confirmation).
- For each browser/device and checkout step combination, mark it as high, medium or low risk for cross-browser bugs, based on how complex or custom the UI is at that step.
- Decide which high and medium risk combinations will be covered by an automated test, and which will be checked manually on a schedule.
- Write one sentence per cell explaining the decision.
Expected outcome: A documented, justified test matrix distinguishing automated coverage from manual exploratory coverage, usable as a template for a real project's cross-browser strategy.
Quiz
1. Why do the same HTML, CSS and JavaScript sometimes behave differently in different browsers?
- Because each browser uses its own rendering engine and JavaScript engine, which may implement a given feature differently or on a different timeline
- Because web standards are not published publicly
- Because only one browser is allowed to run JavaScript at a time
- Because CSS is interpreted differently depending on the user's operating system language setting
Show answer
A. Because each browser uses its own rendering engine and JavaScript engine, which may implement a given feature differently or on a different timeline
Rendering engines (such as Blink, Gecko and WebKit) and their JavaScript engines are built and maintained separately, so they can differ in which features they support, how they interpret edge cases, and when a given feature ships.
2. What is the main advantage of feature detection over browser sniffing (checking the browser's name or version)?
- Feature detection is faster to type
- Feature detection checks whether a specific capability is actually available, which is more reliable than inferring capability from a name or version string that can be spoofed or outdated
- Browser sniffing works in more browsers than feature detection
- Feature detection removes the need for any fallback code
Show answer
B. Feature detection checks whether a specific capability is actually available, which is more reliable than inferring capability from a name or version string that can be spoofed or outdated
A user agent string can be spoofed, missing, or simply out of date relative to what the browser actually supports, while checking directly for an API or CSS feature tells you what is really available.
3. Which category of UI element is most often rendered by the operating system rather than purely by the page's own CSS, making it a common source of cross-browser visual differences?
- Plain paragraph text
- Native form controls such as date pickers, color pickers and select dropdowns
- Background colors set with hex codes
- HTML comments
Show answer
B. Native form controls such as date pickers, color pickers and select dropdowns
Controls like date pickers, color pickers and multi-select dropdowns are frequently drawn by the operating system or the browser's own UI layer, so your CSS can only partially influence their appearance, and they look different across platforms and engines.
4. In a Playwright configuration file, what does adding 'chromium', 'firefox' and 'webkit' as separate projects achieve?
- It installs three unrelated testing frameworks
- It runs the exact same test suite against three different rendering engines, giving cross-engine coverage from one command
- It only changes the reporter format used for test output
- It disables parallel test execution
Show answer
B. It runs the exact same test suite against three different rendering engines, giving cross-engine coverage from one command
Defining multiple projects in a Playwright config lets the same test files run against Chromium, Firefox and WebKit, so you get coverage across the three major engine families without duplicating test code.
5. Why is a risk-based test matrix generally preferred over trying to test every possible browser and device combination?
- Because the number of possible combinations is effectively unlimited, so prioritizing by audience relevance and feature complexity focuses effort where bugs are most likely and most costly
- Because risk-based matrices require no manual testing at all
- Because automated tools cannot run on more than one browser
- Because regulators require a risk-based approach for all software
Show answer
A. Because the number of possible combinations is effectively unlimited, so prioritizing by audience relevance and feature complexity focuses effort where bugs are most likely and most costly
Exhaustive coverage of every browser, version, device and screen size is not practical, so a risk-based matrix prioritizes the browsers your actual audience uses and the parts of the application most likely to expose engine-specific bugs, with everything else covered more lightly or manually.