javascriptautomated-testscypresscypress-custom-commandscypress-intercept

How to clear browser cache within a Cypress test


Background:

Hey all, I have a Cypress test I'm trying to write that should check whether an image URL has been called, after the image itself has been clicked on.

Currently I run the test and it finds the image URL on the first run but when it is re-run, the test fails to find it because the image has already been saved to the browser cache.

Is there a way to clear the browser cache before each Cypress test so that the image URL will always get called/found when I run the test?

Current solution:

it('should request webp image format for zoomed pdp image', () => {
  cy.intercept(
    '**/cdn/cs/set/assets/blt2bd0405f3cb027cb/5005769.jpg?fit=bounds&format=webply&quality=80&width=1600&height=1600&dpr=1.5'
  ).as('zoomedImageRequest');
  cy.gotoPage('product/transparent-red-sorting-case-to-go-5005769');
  cy.get(pdp.pdpImage).click();
  cy.wait('@zoomedImageRequest').then((xhr) => {
    const zoomedImageUrl = xhr.response.url;
    expect(zoomedImageUrl).to.contain('format=webply');
  });
});

Solution

  • Try clearing the network cache at the top of the test,

    cy.wrap(Cypress.automation('remote:debugger:protocol', {
      command: 'Network.clearBrowserCache',
    }))
    
    cy.intercept(...).as('zoomedImageRequest');
    
    cy.gotoPage('product/transparent-red-sorting-case-to-go-5005769');
    cy.get(pdp.pdpImage).click();
    cy.wait('@zoomedImageRequest').then((xhr) => {
      const zoomedImageUrl = xhr.response.url;
      expect(zoomedImageUrl).to.contain('format=webply');
    });
    

    There is also a header that can be removed, but I found it not to be consistent

    cy.intercept('...', req => {
      delete req.headers['if-none-match'];
    })