Device Emulation
Relevant source files
The following files were used as context for generating this wiki page:
- packages/playwright-core/src/server/deviceDescriptors.ts
- packages/playwright-core/src/client/browserContext.ts
- tests/library/browsercontext-device.spec.ts
- tests/library/geolocation.spec.ts
- packages/playwright/types/test.d.ts
- README.md
- tests/library/inspector/cli-codegen-test.spec.ts
- tests/library/browsercontext-user-agent.spec.ts
Device emulation in Playwright allows developers to simulate various mobile and desktop devices to test the behavior and responsiveness of web applications across different screen sizes, user agents, and device capabilities. This is achieved by configuring a BrowserContext with a set of device-specific parameters, such as viewport size, user agent, device scale factor, touch support, and geolocation.
Playwright provides a collection of pre-configured device descriptors for popular devices like iPhone, Pixel, and Galaxy models. These descriptors can be easily applied when creating a new browser context or within a test configuration, ensuring that tests run in an environment that closely mimics a real device. This capability is crucial for cross-browser and cross-device web automation and testing, enabling the detection of device-specific issues.
Core Concepts
Device emulation is centered around the BrowserContext, which can be configured with specific properties to mimic a device. The primary mechanism for this is the playwright.devices object, which contains a set of predefined DeviceDescriptor objects.
Device Descriptors
A DeviceDescriptor is an interface that defines the properties of a device to be emulated. These properties are used to configure a BrowserContext.
The diagram below illustrates the structure of the DeviceDescriptor.
This class diagram shows the main properties of the DeviceDescriptor interface.
Sources: packages/playwright-core/src/server/deviceDescriptors.ts
The key properties of a DeviceDescriptor are:
| Property | Type | Description |
|---|---|---|
userAgent | string | The user agent string of the device's browser. |
viewport | object | The viewport size (width, height) of the device screen. |
deviceScaleFactor | number | The device scale factor (pixel ratio). |
isMobile | boolean | Whether the device is considered a mobile device. This affects the meta viewport tag. |
hasTouch | boolean | Whether the device supports touch events. |
defaultBrowserType | 'chromium' | 'firefox' | 'webkit' | The default browser type recommended for emulating this device. |
| Sources: packages/playwright-core/src/server/deviceDescriptors.ts |
Playwright includes a large list of built-in device descriptors. For example, the descriptor for the "Pixel 7" is defined as:
// from packages/playwright-core/src/server/deviceDescriptors.ts
'Pixel 7': {
userAgent: 'Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Mobile Safari/537.36',
viewport: { 'width': 412, 'height': 915 },
deviceScaleFactor: 2.625,
isMobile: true,
hasTouch: true,
defaultBrowserType: 'chromium',
},
Sources: packages/playwright-core/src/server/deviceDescriptors.ts:1829-1836
Applying Emulation
There are several ways to apply device emulation settings in Playwright.
Using browser.newContext()
You can create a new BrowserContext with device emulation settings by spreading a device descriptor from playwright.devices.
This flowchart shows the process of creating a new emulated browser context and page.
Sources: tests/library/browsercontext-device.spec.ts:17-21
Here is a code example:
// From tests/library/browsercontext-device.spec.ts
const context = await browser.newContext({
...playwright.devices['iPhone 6'],
});
const page = await context.newPage();
Sources: tests/library/browsercontext-device.spec.ts:17-21
You can also override or add properties to the device descriptor. For example, to set a specific geolocation:
// From README.md
import { test, devices } from '@playwright/test';
test.use({
...devices['iPhone 13 Pro'],
locale: 'en-US',
geolocation: { longitude: 12.492507, latitude: 41.889938 },
permissions: ['geolocation'],
})
Sources: README.md:104-110
Using Playwright Test test.use()
The recommended way to apply device emulation for tests is through the test.use() configuration. This can be done at the test file level or within a test.describe block.
// From packages/playwright/types/test.d.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
projects: [
{
name: 'Mobile Chrome',
use: devices['Pixel 5'],
},
{
name: 'Mobile Safari',
use: devices['iPhone 12'],
},
],
});
Sources: packages/playwright/types/test.d.ts:70-87
Using Codegen CLI
The Playwright Codegen tool can generate code with device emulation settings using the --device command-line flag.
npx playwright codegen --device="Pixel 2"
This will generate test code that includes the device configuration:
// From tests/library/inspector/cli-codegen-test.spec.ts
import { test, expect, devices } from '@playwright/test';
test.use({
...devices['Pixel 2'],
});
test('test', async ({ page }) => {
// ... generated test code
});
Sources: tests/library/inspector/cli-codegen-test.spec.ts:36-44
Specific Emulation Features
Geolocation
Playwright can emulate geolocation by providing latitude and longitude coordinates. This requires granting the 'geolocation' permission to the context.
This sequence diagram illustrates how emulated geolocation is provided to a page during a test.
Sources: tests/library/geolocation.spec.ts:12-23, README.md:104-115
Example test for geolocation:
// From tests/library/geolocation.spec.ts
test('should work', async ({ page, context, server }) => {
await context.grantPermissions(['geolocation']);
await page.goto(server.EMPTY_PAGE);
await context.setGeolocation({ latitude: 10, longitude: 20 });
const geolocation = await page.evaluate(() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
resolve({ latitude: position.coords.latitude, longitude: position.coords.longitude });
})));
expect(geolocation).toEqual({ latitude: 10, longitude: 20 });
});
Sources: tests/library/geolocation.spec.ts:12-23
User Agent and Client Hints
Setting a userAgent in the context options will correctly set the User-Agent HTTP header for all requests made from the page, including those from subframes. For Chromium, it also affects the navigator.userAgentData and sec-ch-ua-* headers to match the emulated device.
For example, emulating a 'Pixel 7' will set sec-ch-ua-mobile to ?1 and sec-ch-ua-platform to "Android".
// From tests/library/browsercontext-user-agent.spec.ts
const context = await browser.newContext(playwright.devices['Pixel 7']);
const page = await context.newPage();
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
page.goto(server.EMPTY_PAGE),
]);
expect.soft(request.headers['sec-ch-ua-mobile']).toBe(`?1`);
expect.soft(request.headers['sec-ch-ua-platform']).toBe(`"Android"`);
Sources: tests/library/browsercontext-user-agent.spec.ts:107-116
Other Emulated Properties
Device descriptors also configure other important properties:
isMobile: Affects whether themeta viewporttag is respected.hasTouch: Enables touch events, which is crucial for testing mobile-specific interactions.colorScheme: Can be set to'light'or'dark'to emulate user's system preference.locale: Affectsnavigator.languageand theAccept-Languageheader.
These can be set individually or as part of a device preset.
Conclusion
Playwright's device emulation is a powerful feature for ensuring web applications are robust and function correctly across a wide range of devices. By providing a comprehensive set of pre-configured device descriptors and a flexible API to apply and customize emulation settings, it simplifies the process of cross-device testing. Developers can easily integrate device emulation into their testing workflow, whether through direct context creation, test configuration, or the command-line interface, leading to higher quality and more reliable web applications.