在Cypress中多次拦截同一API调用 [英] Intercept the same API call multiple times in Cypress

查看:33
本文介绍了在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

这篇关于在Cypress中多次拦截同一API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆