在Cypress中多次拦截同一API调用

是否可以在同一个测试中使用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被调用的第2次。但是,第二个cy.wait将立即继续,因为第一个API调用与第二个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')

})

APP

<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>

您可以在Cypress日志中看到它,

命令 调用编号 发生(橙色标记)
等待 @Call1 1
等待 @call2
等待 @Call1 2

相关文章