Mock Geolocation
Overview
When your website or web-application is changing based on the location from which it is being accessed, it becomes important to test your website for all these locations. With Chrome DevTools Protocol support now available in Selenium 4, Nightwatch supports mocking the geolocation of the browser during the test run with just one command.
This will allow you to access and test the different versions of your website served at different locations, while testing from a single location.
Mock Geolocation
Mocking the geolocation of your browser allows you to override the location sent by your browser to your website, so that your website can respond with a version meant to be served at that location.
All you need to do is call the browser.setGeolocation()
command with the required parameters before navigating to your website and the version of website meant for the requested location will be served back to you.
setGeolocation()
accepts an object as its first argument. The specifications of the object are as follows:
key | type | default | description |
---|---|---|---|
latitude |
number | Latitude of the geolocation to be set. | |
longitude |
number | Longitude of the geolocation to be set. | |
accuracy Optional |
number | 100 | Expected accuracy while mocking the geolocation. |
Example
describe('mock geolocation', function() {
it('sets the geolocation to Tokyo, Japan', () => {
browser
.setGeolocation({
latitude: 35.689487,
longitude: 139.691706,
accuracy: 100
})
.navigateTo('https://www.gps-coordinates.net/my-location')
.pause(3000);
});
});
Reset Geolocation
After overriding the geolocation of your browser, if you now want to reset the geolocation of the browser back to the original during the same test run, you can do so by using the command browser.setGeolocation()
again, but without any arguments this time.
Example:
describe('mock and reset geolocation', function() {
it('sets the geolocation to Tokyo, Japan and then resets it', () => {
browser
.setGeolocation({
latitude: 35.689487,
longitude: 139.691706,
accuracy: 100
}) // sets the geolocation to Tokyo, Japan
.navigateTo('https://www.gps-coordinates.net/my-location')
.pause(3000)
.setGeolocation() // resets the geolocation
.navigateTo('https://www.gps-coordinates.net/my-location')
.pause(3000);
});
});