获取点击后发生的API响应

问题描述 投票:0回答:1

我想获取单击按钮时收到的 api 响应。 在我的用例中,单击按钮后,响应数据将加载到页面上。 我需要在单击按钮时获取响应数据,而不是测试加载的页面。 我如何使用 Cypress 执行此操作?

api cypress response
1个回答
0
投票

正如 jonrsharpe 提到的,您可以使用

cy.intercept()
来侦听请求,然后在拦截的别名上使用
cy.wait()
来检索数据。

下例中所做的假设通过注释指出

cy.intercept('/foo') // assumes request is made to something like www.my-url.com/foo
  .as('foo'); // assign the intercept an alias
cy.get('button') // find the button
  .click() // and click it
cy.wait('@foo') // wait for the request to finish
  .then((interception) => {
    // Assertions on the request here
    // Convenience variable assignment
    const { body } = interception.response
    expect(body).to.not.be.null;
  });
© www.soinside.com 2019 - 2024. All rights reserved.