在 Cypress 中多次拦截相同的 API 调用

Intercept the same API call multiple times in Cypress

是否可以在同一个测试中使用cy.intercept拦截同一个API调用多次?我尝试了以下方法:

cy.intercept({ pathname: "/url", method: "POST" }).as("call1")
// ... some logic
cy.wait("@call1")

// ... some logic

cy.intercept({ pathname: "/url", method: "POST" }).as("call2")
// ... some logic
cy.wait("@call2")

我希望 cy.wait("@call2") 会等待 API 第二次被调用。但是,第二个 cy.wait 将立即继续,因为第一个 API 调用与第二个相同。

当您设置相同的拦截时,第一个拦截将捕获所有呼叫。但是您可以多次等待第一个别名。

这是一个(相当)简单的例子

规格

Cypress.config('defaultCommandTimeout', 10); // low timeout
                                             // makes the gets depend on the waits 
                                             // for success

it('never fires @call2',()=>{

  cy.intercept({ pathname: "/posts", method: "POST" }).as("call1")
  cy.intercept({ pathname: "/posts", method: "POST" }).as("call2")

  cy.visit('../app/intercept-identical.html')
  
  cy.wait('@call1')                               // call1 fires 
  cy.get('div#1').should('have.text', '201')

  cy.wait('@call2')                               // call2 never fires
  cy.wait('@call1')                               // call1 fires a second time
  cy.get('div#2').should('have.text', '201')

})

应用程序

<body>
  <div id="1"></div>
  <div id="2"></div>
  <script>

    setTimeout(() => {
      fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        body: JSON.stringify({ title: 'foo', body: 'bar', userId: 1 }),
        headers: { 'Content-type': 'application/json; charset=UTF-8' },
      }).then(response => {
        document.getElementById('1').innerText = response.status;
      })
    }, 500)
  
    setTimeout(() => {
      fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        body: JSON.stringify({ title: 'foo', body: 'bar', userId: 2 }),
        headers: { 'Content-type': 'application/json; charset=UTF-8' },
      }).then(response => {
        document.getElementById('2').innerText = response.status;
      })
    }, 1000)

  </script>
</body>

你可以在赛普拉斯日志中看到它,

command call# occurrence (orange tag)
wait @call1 1
wait @call2
wait @call1 2

你有很多方法可以做到这一点:

  1. 为截获的同一端点创建唯一别名

    cy.intercept({ pathname: "/posts", method: "POST" }).as("call")
    
    //First Action
    cy.get("button").click()
    cy.wait("@call").its("request.url").should("contain", "somevalue")
    
    //Second Action
    cy.get("button2").click()
    cy.wait("@call").its("request.url").should("contain", "othervalue")
    
  2. 创建特定的en端点,可以使用glob模式生成动态端点

    //notice path key instead of pathname
    cy.intercept({path: "/post*parameter1=true", method: "POST"}).as("call1")
    
    //First Action
    cy.get("button").click()
    cy.wait("@call1").its("request.url").should("contain", "somevalue")
    
    cy.intercept({path: "/post*parameter2=false", method: "POST"}).as("call2")
    
    //Second Action
    cy.get("button2").click()
    cy.wait("@call2").its("request.url").should("contain", "othervalue")
    
  3. 验证结束时调用的所有端点

     cy.intercept({ pathname: "/posts", method: "POST" }).as("call")
    
     //First Action
     cy.get("button").click()
     cy.wait("@call")
    
     //Second Action
     cy.get("button2").click()
     cy.wait("@call")
    
     //you can add the number of request at the finish of alias
     cy.get("@call.1").its("request.url").should("contain", "somevalue")
     cy.get("@call.2").its("request.url").should("contain", "othervalue")
    
     //another option instead of add the number of request maybe use the position in letters, but I think that it only works for first and last.
     cy.get("@call.first").its("request.url").should("contain", "somevalue")
     cy.get("@call.last").its("request.url").should("contain", "othervalue")
    

如果您的要求在某些方面有所不同,我会使用 aliasing on individual requests。在我的例子中,我向同一条路线发出了多个 post 请求,但主体略有不同。所以我最终做了这样的事情:

cy.intercept("POST", '/your_route', (req) => {
    if (req.body.hasOwnProperty('your_prop')) {
        req.alias = 'your_alias';
        req.reply(your_response);
    }
});

这将拦截并存根一个 post 请求,该请求在正文中包含所需的 属性。

// wait for 2 calls to complete
cy.wait('@queryGridInput').wait('@queryGridInput')
// get
cy.get("@queryGridInput.all").then((xhrs)=>{});

@alias.all 将等待所有实例完成。 它将 return 包含所有匹配的@alias 的 xhrs 数组。

https://www.cypress.io/blog/2019/12/23/asserting-network-calls-from-cypress-tests/

Cypress: I am trying to intercept the 10 calls which originate from 1 button click but the cy.wait().should is only tapping the last call