我想获取单击按钮时收到的 api 响应。 在我的用例中,单击按钮后,响应数据将加载到页面上。 我需要在单击按钮时获取响应数据,而不是测试加载的页面。 我如何使用 Cypress 执行此操作?
正如 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;
});