Using Geolocation in Playwright tests
In this blog post, we go over the basics of how to use the Geolocation API with Playwright.
You might have already written some code to get access to the user's location. Even if you haven't, you probably have already seen the browser asking for permission to access your location. This is not different in Playwright tests.
When your application tries to access the location during a test, the same prompt will appear.
This is blocking the test execution, and after a few seconds, it results in a timeout. Luckily we don't have to click the "Allow" button manually for every test.
Giving permission to use the location link
To get rid of the prompt, we need to configure Playwright to have permission to use the location. This is done in the Playwright config file, via the use option.
While this grants permission to the browser context to read the user's location, it doesn't actually set the location.
Setting the location link
We're over the first hurdle, but we still need to set the location.
Provide a global geolocation configuration link
To set the location globally, we set the geolocation
option in the Playwright config file to emulate a user's location.
When we run the test now, the application receives the coordinates and the location is set.
Stubbing the location for a specific test(s) link
To set the location for a specific test, inject the browser context in the test (context
), and set the location with the setGeolocation()
method.
When multiple tests need to overwrite the location, you can also set the location for all tests within a file.
Or, set the location for all tests within a describe
block.
Feel free to update this blog post on GitHub, thanks in advance!
Join My Newsletter (WIP)
Join my weekly newsletter to receive my latest blog posts and bits, directly in your inbox.
Support me
I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.