如何根据响应匹配截取 [英] How to match intercept on response
本文介绍了如何根据响应匹配截取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
30000ms后重试超时:预期"Running"等于"Complete"
因此测试失败,因为状态为Running,而预期状态为Complete。在这种情况下如何增加超时?
cy.intercept('GET', Cypress.config().baseUrl + 'api/scans/' + scanID).as('getStatus');
cy.visit('/')
cy.wait('@getStatus', {responseTimeout: 80000}).its('response.body.status')
.should('eq', 'Completed')
推荐答案
从Hiram的回答继续,如果您不知道要等待多少个请求,可以使用函数重复等待,直到达到所需的状态。
当然,";Completed&Quot;状态可能永远不会到达,因此您需要设置要检查的最大请求/响应数(代替超时)。
为了模拟您的情况,我使用了一个在300ms间隔内发出三个请求的简单网站。
响应正文的ID恰好与请求中的参数相同,因此我们希望等待response.body.id === 3
。
3个请求的简单应用
<script>
setTimeout(() => fetch('https://jsonplaceholder.typicode.com/todos/1'), 300)
setTimeout(() => fetch('https://jsonplaceholder.typicode.com/todos/2'), 600)
setTimeout(() => fetch('https://jsonplaceholder.typicode.com/todos/3'), 900)
</script>
测试
it('waits for a particular response', () => {
cy.visit('../app/intercept-last.html')
cy.intercept('**/jsonplaceholder.typicode.com/todos/*')
.as('todos')
function waitFor(alias, partialResponse, maxRequests, level = 0) {
if (level === maxRequests) {
throw `${maxRequests} requests exceeded` // fail the test
}
cy.wait(alias).then(interception => {
const isMatch = Cypress._.isMatch(interception.response, partialResponse)
if (!isMatch) {
waitFor(alias, partialResponse, maxRequests, level+1)
}
})
}
waitFor('@todos', { body: { id: 3 } }, 100) // if no error, value has arrived
cy.get('@todos.last') // now use get() instead of wait()
.its('response.body.id').should('eq', 3)
})
您的测试
cy.intercept('GET', Cypress.config().baseUrl + 'api/scans/' + scanID)
.as('getStatus')
cy.visit('/')
function waitFor(alias, partialResponse, maxRequests, level = 0) {
if (level === maxRequests) {
throw `${maxRequests} requests exceeded`
}
cy.wait(alias).then(interception => {
const isMatch = Cypress._.isMatch(interception.response, partialResponse)
if (!isMatch) {
waitFor(alias, partialResponse, maxRequests, level+1)
}
})
}
const timeout = 80_000 // timeout you want to apply
const pollingRate = 500 // rate at which app sends requests
const maxRequests = (timeout / pollingRate) + 10; // number of polls plus a few more
waitFor('@getStatus', { body: { status: 'Completed' } }, maxRequests)
cy.get('@getStatus.last')
.its('response.body.status').should('eq', 'Completed')
这篇关于如何根据响应匹配截取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文