[英]Cypress intercept all image requests with regex url
I want to intercept all image GET requests and check if they have 200 status code.我想拦截所有图像 GET 请求并检查它们是否有 200 个状态码。 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.
我想要一个正则表达式 url 来捕获所有图像请求。
After suggested solutions I could wrote a test like Expect 5 images to be loaded on this page
.在建议的解决方案之后,我可以编写一个测试,例如
Expect 5 images to be loaded on this page
。 Intercepts the 4 svg and 1 jpg request successfully.成功拦截 4 svg 和 1 jpg 请求。
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.但是我仍然想知道如果我有任何带有非 200 状态代码的图像请求,如何放置测试逻辑。 Is there a failed image request?
是否有失败的图像请求?
I'm afraid it is a bit tricky, and you are kind of limited by the way intercept
behaves.恐怕这有点棘手,而且您受到
intercept
行为方式的限制。 Your command will match the first extension type requests, eg .png
and will omit the others.您的命令将匹配第一个扩展类型请求,例如
.png
并忽略其他的。 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);
})
})
Using a regex with cy.intercept()
is possible, but don't surround it with quotes.可以使用带有
cy.intercept()
的正则表达式,但不要用引号括起来。
Also you can't use **/*
pattern which is part of the Glob pattern (a different way to specify wildcard patterns).此外,您不能使用作为 Glob 模式一部分的
**/*
模式(指定通配符模式的不同方式)。
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.