3

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');
  });
});
Fody
  • 23,754
  • 3
  • 20
  • 37
devDan
  • 45
  • 1
  • 5

1 Answers1

4

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'];
})
Fody
  • 23,754
  • 3
  • 20
  • 37
  • 2
    I can't tell you how long I've been searching for a solution that clears browser cache in Cypress and actually works. My intercepts weren't doing anything because my api requests were caching. This works great! – BSK Jan 05 '23 at 20:59