Home > Back-end >  Cypress intercept all image requests with regex url
Cypress intercept all image requests with regex url

Time:07-06

I want to intercept all image GET requests and check if they have 200 status code. My try so far.

cy.intercept({ method: 'GET' , url: '/**/*.(png|svg|jpeg|webp|jpg)/'}).as('imageRequest')
cy.get('@imageRequest').its('response.statusCode').should('eq', 200)

It fails to intercept the image requests. I want one regex url to capture all image requests.

CodePudding user response:

I'm afraid it is a bit tricky, and you are kind of limited by the way intercept behaves. Your command will match the first extension type requests, e.g. .png and will omit the others. A potential solution will be to listen to each extension type, but only if you are sure these extension types are registered/called, so:

const imageExtensionTypes = ['png', 'svg', 'jpeg', 'webp', 'jpg'];

imageExtensionTypes.forEach(extensionType => {
   cy.intercept(`/**/*.${extension}`).as(`${extensionType}_imageRequest`)
})
 ...

imageExtensionTypes.forEach(extensionType => {
   cy.wait(`@${extensionType}_imageRequest`).then(({ response }) => { 
      expect(response.statusCode).to.eq(200);
   })
})

CodePudding user response:

Using a regex with cy.intercept() is possible, but don't surround it with quotes.

Also you can't use **/* pattern which is part of the Glob pattern (a different way to specify wildcard patterns).

See Matching url

cy.intercept({ 
  method: 'GET', 
  url: /\/. \.(png|svg|jpeg|webp|jpg)/            // add the regex directly
}).as('imageRequest')

// cy.visit() or button click()

cy.get('@imageRequest').its('response.statusCode').should('eq', 200)

If you already have the regex pattern specified as a string, you can convert it like this

const pattern = '\/. \.(png|svg|jpeg|webp|jpg)'   // the pattern given as a string
const regex = new RegExp(pattern)                 // make a regex from the pattern
 
cy.intercept({ 
  method: 'GET', 
  url: regex
}).as('imageRequest')
  • Related