javascript - 在 Cypress 测试中断言/检查 stub 请求的轮询率

标签 javascript automated-tests cypress e2e-testing cypress-intercept

我有一个 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/

相关文章:

javascript - JQuery 中 document.getElementbyId 的等价物是什么?

javascript - 将 KeyDown 键码转换为字符串 (jQuery)

selenium - 比较测试覆盖率指标以确定实现自动化后的增加/减少

java - Appium Java testNG框架: driver cannot be resolved to a variable

javascript - 如何使用 cypress.io 检查嵌套的阴影元素

regex - 单击 Cypress 中的完全匹配文本

javascript - 覆盖窗口作为函数调用上下文

javascript - 创建动态 ID - JQuery

javascript - 导入类之间的关系

javascript - 发现元素可见后无法使用递归来定位元素