Skip to content

Instantly share code, notes, and snippets.

@jamesfulford
Created March 16, 2020 01:59
Show Gist options
  • Save jamesfulford/26181c332c25d6464c3524510d18e75e to your computer and use it in GitHub Desktop.
Save jamesfulford/26181c332c25d6464c3524510d18e75e to your computer and use it in GitHub Desktop.
Clear Service Workers, Cypress
// From https://github.com/cypress-io/cypress/issues/702#issuecomment-435873135
beforeEach(() => {
if (window.navigator && navigator.serviceWorker) {
navigator.serviceWorker.getRegistrations()
.then((registrations) => {
registrations.forEach((registration) => {
registration.unregister();
});
});
}
});
@csvan
Copy link

csvan commented Dec 12, 2021

Is this actually necessary since Cypress creates a new session on each run?

@brettz9
Copy link

brettz9 commented Dec 1, 2022

I think it is necessary, but I think it is necessary to wait until all registrations have unregistered:

  beforeEach(async () => {
    if (!window.navigator || !navigator.serviceWorker) {
      return null;
    }
    const registrations = await navigator.serviceWorker.getRegistrations();
    return Promise.all(registrations.map((registration) => {
      return registration.unregister();
    }));
  });

Also, on a related topic, FWIW, the section at https://glebbahmutov.com/blog/cypress-tips-and-tricks/#disable-serviceworker mentions how to disable service worker registrations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment