Search code examples
cypressbrowser-cachecy.intercept

How to intercept an image request using cy.intercept


I am trying to set up an intercept for an image, load a page and wait for the request to the image Ultimately I would like to replace the image (just to add context), but for now I would just like to detect the image.

I have read https://docs.cypress.io/api/commands/intercept, and I must be missing something.

My test is (based on https://github.com/cypress-io/cypress-example-recipes/blob/master/examples/stubbing-spying__intercept/cypress/e2e/image-spec.cy.js):

it('matches the base image', () => {
      cy.intercept(
        'GET',
        'https://ichef.bbci.co.uk/ace/standard/480/cpsprodpb/AB35/production/_129792834_gettyimages-1256077146.jpg',
      ).as('image');
      cy.visit('https://www.bbc.co.uk/news/election/2023/england/results');
      cy.wait('@image');
});

The error I get in my test is:

CypressError: Timed out retrying after 5000ms: 'cy.wait()' timed out waiting '5000ms' for the 1st request to the route: 'image'. No request ever occurred. https://on.cypress.io/wait

I am using Cypress version 13.5.0.

I hope I have included enough for my query to make sense. Any help would be gratefully received.


Solution

  • When I ran the sample code it initially passed, then subsequent runs (test runner open) it failed.

    Looking at the devtools Network tab I can see an entry data:image that has a note served from memory cache. I've no idea if this is loading the image, but caching requests can cause cy.intercept() to fail.

    Clearing the browser cache

    This answer by @Fody has a way to clear the browser cache using chrome devtools protocol, which is available as a call to Cypress.automation():

    How to clear browser cache within a Cypress test

    const registerCypressGrep = require('@cypress/grep')
    registerCypressGrep()
    
    it('matches the base image', () => {
    
      cy.wrap(Cypress.automation('remote:debugger:protocol', {
        command: 'Network.clearBrowserCache',
      }))
    
      cy.intercept(
        'GET',
        'https://ichef.bbci.co.uk/ace/standard/480/cpsprodpb/AB35/production/_129792834_gettyimages-1256077146.jpg'
      ).as('image')
      cy.visit('https://www.bbc.co.uk/news/election/2023/england/results');
      cy.wait('@image')
    })
    

    I also set chromeWebSecurity: false in config and specified the chrome browser.

    Burn testing

    Since the test was a little flaky, I decided to burn-test with @cypress/grep

    This is the script in package.json

    "scripts": {
      "burn": "npx cypress run --spec=cypress/e2e/bbc.cy.js --env burn=10 --browser chrome"
    }
    

    This is the burn-test terminal result

    enter image description here