单击按钮后,赛普拉斯等待 API

Geo*_*off 8 javascript reactjs cypress

我已经制作了一个 React 应用程序,它一切正常,我现在正在使用 Cypress 编写一些端到端的测试。

React 应用程序都在同一个 url 上工作,它没有任何路由,并且来自应用程序内部的 api 调用是通过单击按钮来处理的。

该应用程序的基础是最终用户选择一些选项,然后按过滤器查看依赖于所选选项的一些图表。

cy.get('button').contains('Filter').click()
Run Code Online (Sandbox Code Playgroud)

当在 cypress 中按下按钮时,它会运行 3 个按预期返回的 api 调用,但是查看 cypress 文档没有简单的方法,除非我使用cy.wait(15000)不理想的内联,因为有时它们返回得更快,有时它们返回速度较慢,具体取决于所选选项。

编辑 1 我试过使用服务器和路由:

cy.server({ method: 'GET' });
cy.route('/endpoint1*').as('one')
cy.route('/endpoint2*').as('two')
cy.route('/endpoint3*').as('three')
cy.get('button').contains('Filter').click()
cy.wait(['@one', '@two', '@three'], { responseTimeout: 15000 }) 
Run Code Online (Sandbox Code Playgroud)

这给了我错误:

CypressError: Timed out retrying: cy.wait() timed out waiting 5000ms for the 1st request to the route: 'one'. No request ever occurred.
Run Code Online (Sandbox Code Playgroud)

经过进一步调查

更改responseTimeout为 只是timeout修复了错误。

cy.server({ method: 'GET' });
cy.route('/endpoint1*').as('one')
cy.route('/endpoint2*').as('two')
cy.route('/endpoint3*').as('three')
cy.get('button').contains('Filter').click()
cy.wait(['@one', '@two', '@three'], { timeout: 15000 }).then(xhr => {
  // Do what you want with the xhr object
}) 
Run Code Online (Sandbox Code Playgroud)

Bre*_*dan 8

听起来你会想要等待路线。像这样的东西:

cy.server();
cy.route('GET', '/api/route1').as('route1');
cy.route('GET', '/api/route2').as('route2');
cy.route('GET', '/api/route3').as('route3');

cy.get('button').contains('Filter').click();

// setting timeout because you mentioned it can take up to 15 seconds.
cy.wait(['@route1', '@route2', 'route3'], { responseTimeout: 15000 });

// This won't execute until all three API calls have returned
cy.get('#something').click();
Run Code Online (Sandbox Code Playgroud)


Jos*_*man 6

.wait您可以使用超时参数,而不是使用。这样,如果它完成得更快,您就不必等待。

cy.get('button').contains('Filter', {timeout: 15000}).click()
Run Code Online (Sandbox Code Playgroud)

在此处的官方文档中被称为选项参数之一

  • 当然,它添加了更多代码,但是添加的代码使我们更清楚要做什么。它还允许测试访问 api 调用的响应。 (3认同)