cypress - 如何让 cypress 等待依赖于另一个响应的响应?

标签 cypress e2e-testing cypress-intercept

从响应 A (/list.json) 我的应用程序收到一个项目列表。根据 A 的输出,我的应用程序针对各个项目(/one.txt/two.txt、...)发出另一组请求 B。

现在,在我的测试中,我想确保所有响应 B 返回 HTTP 200。

等待(cy.wait)响应 A 没问题。然而,等待响应 B 更困难,因为我必须在收到响应 A 后才开始等待,在那里我了解响应 B。

我尝试了两种选择:

  1. 开始在响应 A 的 cy.wait 内等待 - code ,
  2. 在响应 A 的 cy.wait 之外开始等待 - code

这些都不起作用。使用选项 1 我得到

`cy.wait()` timed out waiting `5000ms` for the 1st request to the route: `one.txt`. No request ever occurred

通过选项 2,即使 /two.txt 不存在,我也获得了通过。看起来响应 B 的 cy.wait 是在收到响应后添加的

最佳答案

由于所有请求都是在访问时触发的,并且是动态的,因此您需要一个处理所有请求的拦截。

对我来说,这意味着添加一些 JavaScript 和动态别名。


// avoid status code 304, disable browser cache
Cypress.automation('remote:debugger:protocol', {
  command: 'Network.clearBrowserCache'
})


describe('spec', () => {
  it('test', () => {
    let items = [];
    cy.intercept('GET', '*', (req) => {

      const slug = req.url.substring(req.url.lastIndexOf('/') + 1)
      if (slug === 'list.json') {
        req.alias = 'list'
      } 
      if (items.includes(slug)) {
        req.alias = 'item'
      }

      req.continue((res) => {
        if (slug === 'list.json')) {
          items = res.body;
        }  
      })
    })

    cy.visit('https://demo-cypress.netlify.app');  

    cy.wait('@list')                          // wait for list
      .then(() => {                           // now items is populated
        for (let item of items) {             // really just need the count
          cy.wait('@item').then(interception => {     // wait n-times
            expect(interception.response.statusCode).to.eq(200);
          })
        }
      })
  })
})

关于cypress - 如何让 cypress 等待依赖于另一个响应的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73580430/

相关文章:

testing - 在 Cypress 的某个元素中查找多个元素

javascript - Cypress ,响应主体为 BLOB 而不是 JSON,但 chrome devtools 中的 JSON

javascript - 是否可以使用专用代码将 .p12 或 .pfx 文件导入到 Selenium Webdriver 中?

automated-tests - 有没有办法在 testcafe studio 上使用 Hook 而无需从另一个测试复制/粘贴?

Cypress 测试 - 不拦截 api 请求

graphql - 如何让 Cypress 动态更新夹具到 graphql 调用

typescript - 等待被拦截的请求未按预期工作

javascript - Cypress - 断言仅存在一个带有文本的元素

angular - 如何在angular2中模拟 Protractor 中的拖放 Action ?

browser - 是否可以使用 Cypress 将 `postMessage` 发送到应用程序?如何传递通过 `postMessage` 接收的数据?