How to Emulate a Specific Geolocation with Playwright
Emulating or changing the geolocation in automated tests is crucial for scenarios where location-specific content, such as pricing rules or location-based features, needs validation.
For instance, e-commerce websites often require location-based testing to ensure that functionalities like local currency conversion and region-specific promotions work as expected.
In today's tip, I'll share a basic Playwright code snippet to emulate a specific geolocation.
const { chromium } = require("playwright");
const mainProcess = async () => {
const browser = await chromium.launch({ headless: false });
const context = await browser.newContext({ permissions: ["geolocation"] });
const page = await context.newPage();
await page.goto("https://practice.expandtesting.com/");
await context.setGeolocation({ latitude: 40.41, longitude: -3.7 });
await page.goto("https://practice.expandtesting.com/geolocation");
await page.click("button#geoBtn");
await page.waitForTimeout(10000);
await browser.close();
};
mainProcess();
Requirements:
- Install Playwright Module: Ensure you have Playwright installed by running:
npm install playwright
- Install Chromium by running:
npx playwright install chromium
Important Notes:
- Permissions: Setting the correct permissions is mandatory for this example to work. Ensure
{ permissions: ["geolocation"] }
is included when creating the browser context. - Running the Code: Save the snippet to a file named
geolocation.js
and run it using
node geolocation.js
Happy coding and testing!