有没有更好的方法断言所有被拦截的请求在 Cypress 中都是成功的?

Is there a better way to assert that all intercepted requests are successful in Cypress?

我正在尝试测试创建对象所涉及的所有 12 个请求是否都成功,到目前为止,这是我认为可行的唯一方法。是否有一种 better/more efficient/more 灵活的方式,不会在我们添加或删除请求时立即中断?

              cy.intercept('/api/**/**').as('objectCreation');
              $button.click();

              cy.wait('@objectCreation').its('response.statusCode').should('eq', 200);
              cy.wait('@objectCreation').its('response.statusCode').should('eq', 200);
              cy.wait('@objectCreation').its('response.statusCode').should('eq', 200);
              cy.wait('@objectCreation').its('response.statusCode').should('eq', 200);
              cy.wait('@objectCreation').its('response.statusCode').should('eq', 200);
              cy.wait('@objectCreation').its('response.statusCode').should('eq', 200);
              cy.wait('@objectCreation').its('response.statusCode').should('eq', 200);
              cy.wait('@objectCreation').its('response.statusCode').should('eq', 200);
              cy.wait('@objectCreation').its('response.statusCode').should('eq', 200);
              cy.wait('@objectCreation').its('response.statusCode').should('eq', 200);
              cy.wait('@objectCreation').its('response.statusCode').should('eq', 200);
              cy.wait('@objectCreation').its('response.statusCode').should('eq', 200);

我想了解有关您的问题的更多详细信息:

  • 请求是否相同?

但是,要回答有关如何简化共享代码片段的问题...您可以创建一个 variable 代表 request 创建尝试并继续调用 cy.intercept()方法并断言其 response 直到达到指定的请求创建数量,如下所示:

const reqObjCreationNum = 0; // reqObjCreationNum object creation attempts number

/**
 * @param {number} reqObjCreationNum - number of object creation attempts
 */
const createObject = ({ reqObjCreationNum }) => {
  cy.intercept('/api/**/**').as('objectCreation');

  while (reqObjCreationNum <= 12) {
    cy.wait('@objectCreation')
      .its('response.statusCode')
      .should('eq', 200);

    reqObjCreationNum += 1;
  }
};

createObject({ reqObjCreationNum });

我建议将来阅读 DRY 编程概念。