A profile in devices sets a consistent group of context options, not just a window size. These are viewport, deviceScaleFactor, isMobile, hasTouch, userAgent and the browser type, so a mobile run is a separate project, and tap() needs hasTouch. It is emulation in a desktop engine, not a real device: no virtual keyboard or real iOS Safari behaviour, so critical mobile flows also need real devices.
Playwright · Emulation
The menu does not open on a phone, yet the desktop tests are green. How do you catch it without a phone?
A user on an iPhone writes to support: the "Menu" button does nothing. The automated tests pass every day, because they run in a 1280×720 window where there is no burger at all: the navigation is laid out in a row. The problem is not the tests but that they have never seen the mobile version. This lesson is about how Playwright models a device, how a profile differs from simply resizing the window, and where the limit of that model lies.
How it works and why.devices is a plain object of browser context options. Playwright creates a separate context for each test, and a profile only presets in it what makes a mobile browser different from a desktop one:
viewport and screen: the size in CSS pixels, on which media queries depend;
deviceScaleFactor: pixel density (2 or 3 on a Retina screen);
isMobile: the browser takes the meta viewport tag into account and behaves as a mobile one (not supported in Firefox);
hasTouch: touch events are available, and without it tap() does not work;
userAgent: read by servers and scripts that detect the device type;
defaultBrowserType: WebKit in an iPhone profile, Chromium in a Pixel profile.
A profile is spread into a project's use, so a mobile run becomes an ordinary config project that the report, the --project filter and CI can see. That is why profiles are not written by hand field by field: the set of values is consistent, and a hand-made one easily forgets something.
Window size only or a full profile
Typical
viewport: { width: 390, height: 844 }
Width-based media queries fire, but touch is off, the userAgent stays desktop and the mobile viewport mode is not enabled. The test is green, while a real phone behaves differently.
Better
...devices['iPhone 15']
Size, pixel density, userAgent, touch and the mobile mode are set together, and the default browser matches the device.
Figure 1. Resizing the window is only the first of the things that make a phone different from a laptop.
Error: locator.tap: hasTouch must be enabled on the browser context before using the touchscreen.
This is a shortened output. The error is direct: the context was created without touch. Here it helps, but in another test of the same "mobile" project the application's touch handlers simply will not fire, and the test passes having checked nothing. The fix: a profile instead of a hand-made size.
// after: a device profile in the projecttest('the menu opens on tap', async ({ page, isMobile }) => {
test.skip(!isMobile, 'Mobile projects only');
await page.goto('/');
await page.getByRole('button', { name: 'Menu' }).tap();
awaitexpect(page.getByRole('navigation')).toBeVisible();
});
The isMobile fixture lets one test file run in all projects: desktop ones skip mobile scenarios, and mobile ones execute them.
Media emulation. Besides a device, the browser can be given substitute media queries for the page. They are set in a project's use or during a test:
Breakpoints without a profile. To check layout boundaries (375, 768, 1280) page.setViewportSize() is sometimes enough. But some applications read the width once at start, so resizing an already loaded page can differ from opening it at the right size. It is more reliable to move the width into a project or test.use({ viewport }).
Limits. This is emulation in a desktop engine, not a real device.
What emulation checks and what it does not
Yes
Catches
Responsive layout and media queries, the mobile menu, touch through tap(), the dark theme, print, offline, userAgent-based behaviour.
No
Does not catch
Bugs of the real iOS Safari, a virtual keyboard pushing a field, gestures, performance on a weak phone, memory limits.
Figure 2. The iPhone profile runs Playwright's WebKit, not iOS Safari, and the Pixel profile runs a desktop Chromium.
The rest needs real devices or a cloud farm. For comparison: in Cypress cy.viewport() changes the window size, so the "mobile" mode there is also only a partial model; Playwright's set is wider, but the principle is the same.
Common mistakes.
Believing that a green mobile project guarantees it works on an iPhone: the engine differs from real Safari, and there is no virtual keyboard.
Building a "mobile" mode from viewport alone: without hasTouch and isMobile the application behaves differently, and a tap fails.
Using click() where the logic depends on touch events: a different event arrives, and the bug stays unseen.
Running all tests in all projects without isMobile: mobile scenarios fail on desktop, desktop ones on mobile.
Sharing screenshots between devices: baselines must be separate for each project.
Check yourself
A project has use: { viewport: { width: 390, height: 844 } }, a test calls tap() and fails. What is wrong and what should change?
Answer
The context was created without hasTouch, so tap is not supported. The simplest fix is a device profile (...devices['iPhone 15']): it sets touch, userAgent and the mobile mode together. A window size alone does not change everything that makes a phone different from a laptop.
The mobile project is green, but iPhone users complain that the keyboard covers the "Amount" field. Why did the test not see it?
Answer
Emulation sets the size, touch and userAgent, but it does not reproduce the virtual keyboard or the specifics of the real iOS Safari: it is Playwright's WebKit build on a desktop. Such bugs are caught on a real device or in a cloud farm, while Playwright keeps what is reproducible: layout and logic.
Related lessons: “Configuration and projects”, “Geolocation, permissions, locale and time zone”, “Visual tests: toHaveScreenshot”.
In an interview.Junior: I run mobile scenarios as a separate project with devices, for example iPhone or Pixel: Playwright sets the size, userAgent and touch. Middle/Senior: I understand it is emulation: the engine is a desktop one, with no virtual keyboard, gestures or real performance, so I additionally check critical mobile flows on real devices. I run one set of tests in all projects and separate scenarios with isMobile, and I check the dark theme, print and offline through emulateMedia and setOffline.
Geolocation, permissions, locale and time zone
Locale, time zone, geolocation and permissions are set with explicit context options so that a result does not depend on the machine. Without them the browser takes locale and time zone from the machine, so a test green in Kyiv can fail in UTC. timezoneId does not change the Node process time zone, so the expected date is computed with Intl and an explicit timeZone.
Playwright · Emulation
The test is green in Kyiv but fails in CI on a server. What differs there: the date, locale or time zone?
A transaction is made at 00:30 Kyiv time on 11 March. A developer writes the expectation "11.03.2026" and sees a green test. In CI on a server in UTC the same test fails: the page shows 10.03.2026. The bug is neither in the application nor in the test: the test silently depended on the settings of the machine it runs on. This lesson is about fixing the browser environment (locale, time zone, geolocation, permissions) so the result does not depend on where the run happens.
How it works and why. For each test Playwright creates a new browser context, and the environment in it is set by context options. If they are not specified, the browser takes the locale and the time zone from the machine, so a laptop and a CI image behave differently. Explicit options remove that:
locale affects navigator.language, the Accept-Language header and the formatting of numbers and dates through Intl;
timezoneId changes the browser's time zone (new Date(), Intl.DateTimeFormat), but not the zone of the Node process that runs the test code itself;
geolocation sets the coordinates that navigator.geolocation returns;
permissions allows browser APIs, for example geolocation or clipboard-read.
Geolocation without a permission does not work: the coordinates are set, but the application gets a refusal. So maps need both options. locale and timezoneId are set when the context is created: through test.use or a project, not in the middle of a test. Geolocation and permissions can also be changed during a test.
Permissions are granted through permissions in the config or a test, or through context.grantPermissions(['clipboard-read'], { origin }), and reset with context.clearPermissions(). The set of supported permissions differs slightly between browsers. The scenario "the user denied geolocation" is checked by simply not granting the permission: the application must show a clear message and not hang.
One moment, different calendar days
Figure 1. The same moment in different zones gives a different calendar date: a test with a hard-coded date fits only one of them.
Example: the Kyiv test fails in UTC. Suppose the statement page builds the date on the client through Intl in the browser's time zone, and the transaction arrives from the server as paidAt: 2026-03-10T22:30:00Z (fixed test data or a mock).
// before: the expectation is written for Kyivtest('transaction date', async ({ page }) => {
await page.goto('/statement');
awaitexpect(page.getByRole('row', { name: /Transfer/ }))
.toContainText('11.03.2026');
});
This is a shortened output. Read it like this: the application did not break, the browser in CI simply runs in UTC, and for it the moment is still "10 March". The right fix has two parts. First, the zone is fixed so that the run is reproducible. Then the expected value is calculated for that zone through Intl with an explicit timeZone rather than typed as text.
// after: the zone is set, the expectation is derived from itconst paidAt = newDate('2026-03-10T22:30:00Z');
const fmt = { day: '2-digit', month: '2-digit', year: 'numeric' } asconst;
const zones = ['Europe/Kyiv', 'America/New_York', 'Pacific/Auckland'];
for (const timezoneId of zones) {
test.describe('statement in the zone ' + timezoneId, () => {
test.use({ timezoneId, locale: 'uk-UA' });
test('the date matches the user zone', async ({ page }) => {
const expected = newIntl.DateTimeFormat('uk-UA', {
...fmt,
timeZone: timezoneId,
}).format(paidAt);
await page.goto('/statement');
awaitexpect(page.getByRole('row', { name: /Transfer/ }))
.toContainText(expected);
});
});
}
Kyiv expects 11.03.2026, New York 10.03.2026, Auckland 11.03.2026. If the application wrongly shows the date in UTC, at least Kyiv fails, and the bug does not hide behind a coincidence of zones.
Locale and number formats. With locale: 'uk-UA' an amount looks like "1 000,50 ₴", and with en-US like "$1,000.50". The thousands separator in a formatted string can be a non-breaking space, so comparing with a literal space is unreliable. A regular expression with \s matches both an ordinary and a non-breaking space:
test.use({ locale: 'uk-UA' });
test('amount in the uk-UA format', async ({ page }) => {
await page.goto('/account');
awaitexpect(page.getByTestId('balance')).toHaveText(/1\s000,50\s₴/);
});
Limits and alternatives.locale only tells the browser the language: the translation is done by the application, if it reads navigator.language or Accept-Language. timezoneId does not change the zone of the server or of the test's Node process: new Date() in the test code stays in the machine's zone, so the expected value is calculated explicitly, as in the example. If a specific "now" is needed too, time is fixed separately through page.clock. Cypress and Selenium have no such built-in way for a time zone: there it is usually set through process environment variables or browser settings.
Common mistakes.
Setting geolocation and forgetting permissions: ['geolocation']: the application gets a refusal, and the test checks the wrong thing.
Typing the expected date as text: the test fits one zone and fails in CI.
Comparing an amount with an ordinary space instead of a non-breaking one: the difference is at the character level, while on screen it looks the same.
Checking only one zone: a date that works in Kyiv breaks in the west or the east.
Relying on the machine's locale: the same test formats numbers differently on a laptop and in a CI image.
Check yourself
A test sets geolocation in Lviv, but the application shows "Geolocation access denied". What is missing?
Answer
The permission: permissions: ['geolocation'] in use or context.grantPermissions. Without a permission the browser does not hand over the coordinates, and the application gets a refusal. This is also useful for the opposite scenario: to check the behaviour on refusal, you simply do not grant the permission.
A test expects "11.03.2026", it is green on a laptop in Kyiv and red in CI in UTC. Why, and how to fix it?
Answer
The moment 22:30Z is already 11 March in Kyiv but still the 10th in UTC. The test depends on the machine's zone. Fix timezoneId in test.use and derive the expected value through Intl.DateTimeFormat with the same timeZone, or better, run several zones.
Related lessons: “Devices, viewport and media”, “Clock API: controlling time”, “Configuration and projects”.
In an interview.Junior: For localisation I set locale and timezoneId, and for geolocation both coordinates and a permission in permissions are needed. Middle/Senior: I do not leave the browser environment to the machine, because a test that passed in Kyiv and failed in UTC is flakiness by configuration. I calculate expected dates through Intl with an explicit zone, run several zones at the day boundary, and remember that timezoneId does not change the Node process or the server, while the "current" time I fix through page.clock.
Clock API: controlling time
page.clock replaces the time sources in the browser, including Date and timers, so minutes of waiting are run through in milliseconds. The clock is installed before goto. fastForward fires overdue timers at most once, while runFor executes every tick, so runFor is used for countdowns and setFixedTime gives a stable date. It covers browser time only: a server-side TTL cannot be checked this way, and times are given with a Z suffix.
Playwright · Emulation
A session ends after 15 minutes. Wait for them in a test or wind the time forward?
An application warns about the session ending at the 14th minute of inactivity and logs the user out at the 15th. There are two bad ways to check this: waitForTimeout(15 * 60_000), after which the test fails on a timeout, or not checking at all. There is a third: replace the clock in the browser and "run" the needed minutes in milliseconds. This is what page.clock provides (since version 1.45). Below: what exactly it replaces, how fastForward differs from runFor, and what it cannot do.
How it works and why.clock.install() replaces the built-in time sources in the page: Date, Temporal.Now, setTimeout, setInterval, requestAnimationFrame, requestIdleCallback (and their clear…/cancel… counterparts) and performance. The application does not know about the replacement: it calls the usual APIs, and they return controlled time. Hence the main condition: install the clock before goto, so the application sets its timers into the replaced scheduler from the very start, not into the real one. There are page.clock and context.clock (for the whole context).
clock.install({ time }): install a clock with an initial time. After that, time flows as usual until it is stopped.
clock.pauseAt(time): jump to a moment and stop time; timers do not fire until runFor, fastForward, another pauseAt or resume.
clock.resume(): resume the natural flow.
clock.fastForward(ticks): a jump forward. All the timers that should have fired do fire, but each at most once; it is like closing a laptop lid and opening it later.
clock.runFor(ticks): run time sequentially, executing each timer at its moments; an interval fires as many times as fit.
clock.setFixedTime(time): Date.now() always returns one value, while timers work as usual.
clock.setSystemTime(time): change the current time without firing timers.
The ticks parameter is a number of milliseconds or a string: '08' means eight seconds, '01:00' one minute, '02:34:10' two hours, 34 minutes and ten seconds.
An interval every minute: five minutes ahead
Figure 1. runFor goes through every tick of the interval, while fastForward jumps and runs the overdue timer once.
Example: waiting 14 minutes, and the test dies at second 30. First an attempt "honestly":
You could raise the test timeout to 15 minutes, but the run becomes absurdly long, and every such test multiplies CI time. The clock solves it without waiting. Assumption: the application sets timers for 14 and 15 minutes on load.
install: The clock is replaced before goto: the app reads controlled time from the start.
14 minutes:fastForward jumps 14 minutes in milliseconds, and the app timers that are now due fire.
Warning: The dialog appeared: the web-first assertion waits for it as usual.
One more minute: After the 15th minute the session ends and the app redirects to the login page.
Figure 2. The numbers lead to the explanations of the code lines.
Assertions after the wind-forward stay ordinary web-first ones: they retry until the application updates the DOM. Note the Z suffix in the date: a string without it is interpreted in the time zone of the Node process, so the test gives different results on different machines.
When runFor is needed. The difference shows on counters. An application with a countdown that decrements a number on each tick of an interval will see one tick after fastForward('10:00') (09:59), because the interval fired once. If instead the application recalculates the remainder from Date.now() each time, one tick already shows the right value. It is not always visible in advance, so for countdowns take runFor, which runs all the ticks.
The assumption here: the banner counts 10 minutes from load. pauseAt before goto stops time before the app starts, and then it moves only through runFor, so the test does not depend on the speed of the machine. For a stable date on a page or in a screenshot, setFixedTime is enough.
What the clock sees and what it does not
Yes
Controls
JavaScript in the browser: Date, timers, requestAnimationFrame, performance.now(). A client-side session timer, a countdown, "today" on a page.
No
Does not control
The server, the database, signed tokens with an exp that the backend checks, and what the browser does outside JavaScript, such as cookie expiry.
Figure 3. The clock controls time inside the page. Everything that checks real time on the server stays real.
Limits and alternatives. If the session is closed by the server, after fastForward('16:00') it still considers the session alive: its clock has not changed. Then you need a test endpoint, a short TTL on the test environment or a separate API test. For code that does not depend on the browser (unit tests) there are their own fake-time tools, for example vi.useFakeTimers() or jest.useFakeTimers(); page.clock is made for the page itself.
Common mistakes.
Calling install after goto: the application has already read the real time and set real timers.
Using fastForward for a counter that decrements on each tick: one tick runs.
Expecting the timer on the server to speed up as well.
Leaving waitForTimeout(60_000) where the time could be run through in milliseconds.
Setting the time without Z or an offset: the result depends on the machine's zone.
Check yourself
A countdown decrements the number on each one-second setInterval tick. A test runs fastForward('10:00') and expects "00:00" but sees "09:59". Why?
Answer
fastForward fires overdue timers at most once, so the interval ran one tick. You need runFor('10:00'), which runs every tick. If the application calculated the remainder from Date.now(), the jump would be enough.
After fastForward('16:00') the client popup "Session ended" appeared, but an API request still passes with the same token. Is that a bug in the application?
Answer
No, it is a limit of the tool. The clock replaces time only in the browser, while the server checks the token against its own real time. The server part is checked separately: with a short TTL on the test environment or an API test.
Related lessons: “Geolocation, permissions, locale and time zone”, “expect.poll and toPass: retries for your own logic”, “Visual tests: toHaveScreenshot”, “Timeouts and the priority of settings”.
In an interview.Junior: For time-dependent logic I use page.clock: I set the time before opening the page and wind it forward instead of real pauses. Middle/Senior: I install the clock before goto and choose the method by behaviour: fastForward when only the result matters, runFor when the application counts ticks, setFixedTime for a stable date. I remember it is the browser only, so I check the server TTL and token expiry separately, and I set the time with Z so the run does not depend on the zone.
Visual tests: toHaveScreenshot
toHaveScreenshot compares a screenshot of a page or element with a baseline and catches visual regressions a functional test misses. The comparison is pixel-based with tolerances: threshold, maxDiffPixels, maxDiffPixelRatio. Baselines are generated and checked in one environment, usually the official Docker image, and updated deliberately in a separate commit. Changing data is stabilised, and mask is kept for unimportant areas because it hides a regression.
Playwright · Emulation
The tests are green, yet in production a button slid under the header. How do you catch that automatically?
A functional test checks that a button exists and can be clicked. It will not say that after a CSS change the button crept under the header, a font was replaced with a fallback and an icon disappeared. Visual tests exist for that: await expect(page).toHaveScreenshot() compares a screenshot with a baseline. The price: baselines have to be stored and updated, and a test easily becomes unstable if the page has anything that changes. This lesson is about how the comparison works and what to do so that it is useful rather than noisy.
How it works and why. The assertion does not just take a shot: it first waits for the page to settle. Playwright takes screenshots in a row until two consecutive ones match, and only then compares the result with the baseline. Before the shot, animations are disabled by default (animations: 'disabled': finite animations are completed, infinite ones are reset to the start), and the caret in fields is hidden (caret: 'hide'). The comparison is pixel-based: the pixelmatch library assesses the colour difference of each pixel.
What happens at toHaveScreenshot
Figure 1. The first run always fails: there is no baseline yet. Tolerance is set by threshold, maxDiffPixels and maxDiffPixelRatio.
Tolerance has three knobs. threshold (0.2 by default) sets how much the colour of a single pixel must differ for it to count as different. maxDiffPixels and maxDiffPixelRatio allow a certain number or share of differing pixels; by default they are zero. Globally they are set in the config:
Baselines and the environment. Baselines live next to the test with a project and platform suffix, for example dashboard-chromium-linux.png. Fonts and rendering differ between macOS, Windows and Linux, so baselines are generated and checked in one environment, usually in the official Playwright Docker image. They are updated with npx playwright test --update-snapshots:
docker run --rm --network host --ipc=host -v $(pwd):/work -w /work \
mcr.microsoft.com/playwright:v1.65.0-noble \
npx playwright test --update-snapshots
The image version must match the @playwright/test version, because a browser update changes rendering too. Updating baselines is a deliberate action in a separate commit that a reviewer looks at with their own eyes. If everything is updated automatically, the test stops checking anything.
Example: a test that fails in CI, and how to stabilise it. First a naive version, with baselines generated on a Mac:
Error: A snapshot doesn't exist at .../statement-chromium-linux.png,
writing actual.
This is a shortened output. The baseline on the Mac is named statement-chromium-darwin.png, while Linux looks for a file with the linux suffix, so all visual tests fail because of a missing baseline, not because of a pixel difference. Even with the right baseline such a test is unstable: the statement has an amount, a time and a chat widget. The fix has three steps: baselines from Docker, a component shot instead of a page, and the changing parts hidden or fixed.
// after: a component, a mask, a fixed timetest('statement card', async ({ page }) => {
await page.clock.setFixedTime(newDate('2026-03-10T12:00:00Z'));
await page.goto('/statement');
awaitexpect(page.getByTestId('summary-card')).toHaveScreenshot(
'summary-card.png',
{
mask: [page.getByTestId('balance')],
stylePath: './tests/hide-chat-widget.css',
},
);
});
mask paints the given elements over with a solid colour (pink by default), stylePath attaches CSS only for the duration of the shot, and setFixedTime makes the date on the page constant.
The whole page or one component
Typical
fullPage: true
A large baseline with plenty of changing content (time, ads, chat). A failure does not point to a cause, and any trifle somewhere on the page breaks the test.
Better
locator.toHaveScreenshot()
A small baseline, less noise, a clear cause of failure. Changing parts are masked or fixed through a mock or page.clock.
Figure 2. The smaller the shot area, the fewer reasons for a false failure.
Limits and alternatives.mask hides the area from regressions as well: if the layout of a masked widget breaks, the test will not say so. So it is better to make changing data stable (a mock, page.clock) and mask only what is unimportant. Pixel comparison does not answer the question "what is actually shown here": for the page structure by its ARIA tree there is toMatchAriaSnapshot, which is usually more stable than pixels but does not see visual defects. Cloud services (Percy, Chromatic, Applitools) take over storing, comparing and reviewing changes, but add a dependency and cost. Each Playwright project has its own baselines, so a mobile profile and a dark theme produce separate files.
Common mistakes.
Generating baselines on macOS and checking in a Linux CI: the files differ by the platform suffix, and all tests fail.
Shooting a whole page with ads, time and animated widgets without mask or fixed data.
Raising threshold or maxDiffPixelRatio until the test stops catching real changes.
Updating baselines "blindly" to make CI green.
Masking what actually needs to be checked: the test is green, and the defect stays in the mask.
Check yourself
Baselines were committed from a Mac. In a Linux CI all visual tests fail. What is the message in the log, and what to do?
Answer
"A snapshot doesn't exist … writing actual": baseline files carry a platform suffix (-darwin versus -linux), so Linux looks for different ones. Baselines are generated in the same environment where they are checked, usually in a Playwright Docker image of the same version as the package, and in a separate commit.
The page header has a live clock. Which is better: mask or page.clock.setFixedTime? What is the difference?
Answer
If the look of the clock matters, it is better to fix the time: the content is stable and a layout regression of the clock is visible. mask just covers the area, and a defect in it will never be noticed. Mask what is unimportant or cannot be fixed.
Related lessons: “Devices, viewport and media”, “Clock API: controlling time”, “Artifacts and reports”, “Configuration and projects”.
In an interview.Junior: I write visual tests with toHaveScreenshot: the first run creates a baseline, then Playwright compares with it and shows the difference. Middle/Senior: I generate baselines in Docker so there are no differences between macOS and Linux, and I review updates in a separate commit. I shoot components rather than the page, make changing data stable through mocks and page.clock, and keep mask for what is not worth checking, because it hides a regression in the masked area.