我有一个 Cypress 测试,该测试使用带有 cy.intercept
的 stub 响应。我们拦截的请求正在轮询后端的端点 - 我们每秒发出一个请求,直到响应中的状态属性发生更改。
我对 Cypress 还很陌生,所以我可能对实际可以测试的内容有错误的想法,但是我想检查的是向此端点发出请求的频率,即断言轮询以正确的速率(一次/秒)完成。
这可能与 Cypress 有关吗?或者我应该研究一些其他工具?
这就是我们对网络调用进行 stub 的方式(简化):
cy.intercept(
{
method: 'GET',
path: '/api/user',
},
{
body: {
id: '1',
status: 'UPDATED', // This is the status that eventually stops the polling
// etc.
},
}
).as('getUserUpdated');
cy.intercept(
{
method: 'GET',
path: '/api/user',
times: 2,
},
{
body: {
id: '1',
status: 'CREATED',
// etc.
},
}
).as('getUserCreated');
最佳答案
这是一个简单的脚本,以 1 秒的间隔轮询 api 大约 10 秒
<script>
const intervalId = setInterval(() => {
fetch('/api/user')
}, 1000)
setTimeout(() => {
clearInterval(intervalId)
}, 10_000)
</script>
如果我想使用 cy.intercept() 进行测试,我基本上会使用拦截的回调形式并在其中记录时间。
cy.intercept('/api/user', req => {
polls.push(Date.now() - last)
last = Date.now() // update the last time to record time between polls
req.reply({ id: '1', status: 'UPDATED'})
})
但是第一个间隔时间因 cy.visit()
页面加载而扭曲,因此第二个 cy.interval()
可以捕获并丢弃它 - 但您也可以只是 .slice()
polls 数组。
注意设置 cy.intercept()
的顺序 - 最后设置的一个是 Cypress 检查的第一个(然后由于 {times:1 而在 1 次捕获后过期) }
)。
let last = Date.now()
const polls = []
cy.intercept('/api/user', req => {
polls.push(Date.now() - last)
last = Date.now()
req.reply({ id: '1', status: 'UPDATED'})
})
// This is just to consume the first call
// since the `cy.visit()` distorts the interval
cy.intercept('/api/user', { times: 1 }, req => {
last = Date.now()
req.reply({ id: '1', status: 'UPDATED'})
})
cy.visit('/');
cy.wait(10_000)
.then(() => {
cy.wrap(polls)
.each(poll => {
expect(poll).to.be.closeTo(1000, 50) // best check is +/- 50 ms
})
})
关于javascript - 在 Cypress 测试中断言/检查 stub 请求的轮询率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75070217/