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.
After suggested solutions I could wrote a test like Expect 5 images to be loaded on this page
. Intercepts the 4 svg and 1 jpg request successfully.
cy.intercept({
method: 'GET',
url: /\/.+\.(png|svg|jpeg|webp|jpg)/ // add the regex directly
}).as('imageRequest')
....
const imageCount = 5
cy.get('[data-cy="profile::"]').click()
for (let i = 0; i < imageCount; i++) {
cy.wait('@imageRequest').then(({response}) => {
expect(response.statusCode).to.eq(200);
})
}
But I still wonder how to put the test logic like if I have any image request with non 200 status code. Is there a failed image request?
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')