Background

cypress-browser-permissions plugin has not been updated for 9 months, and the implementation is no longer recognized by Cypress (it is not recognized by version 9.5.0 either, so it does not seem to be a problem caused by migration, so consider re-implementing it).


geo_fail_1.png


It shows that Cypress runs with a count of 0, which means no testcases are identified by Cypress.


geo_fail_2.png


Also my application is calling googleAPIs for location, and the network in China causes location to fail (even if browser permissions are allowed).


So I started looking for alternatives.


Something About cypress-browser-permissions Plugin

For browser permissions, Cypress provides before:browser:launch configuration:
https://docs.cypress.io/api/plugins/browser-launch-api#Modify-browser-launch-arguments-preferences-and-extensions


The original author also used this to control browser permissions:
permissions.png



Successful Alternative


Using cypress-browser-permissions requires the browser to be running in headed mode.
So it is intended to be used in conjunction with xvfb on CI.


And after replacing it with my new method, it can run successfully in CI in headless mode.



Simulation of location failure


Use the method below to throw an error, which can make location to fail.

PS: Since onBeforeLoad will report an error, I cannot successfully locate using this method, although it seems to support mock location from the code.

location_failure.png



Here is part of my script:

describe('geolocation', () => {

function fakeLocation () {
return {
onBeforeLoad (win) {
cy.stub(win.navigator.geolocation, 'getCurrentPosition', (err) => {
throw err({ code: 1 }); // 1: rejected, 2: unable, 3: timeout
});
}
};
}

const url = 'xxx'

it('location_failure', () => {
cy.visit(url, fakeLocation())
...
})
})



Simulation of location success

Use this plugin to configure fixed latitude and longitude for location:
https://www.npmjs.com/package/cypress-visit-with-custom-geolocation



Here is part of my script:

it('location_success', () => {
cy.window().then(win => {
var url = 'xxx'
cy.visitWithCustomGeoLoc(win, url, 32.061707, 118.763232);
location(url) // 填写
})
...
})


This is my execution and it achieved what I needed:
location_success.png