在 Cypress 测试中,如果预期的 XHR 请求未发出,如何重试按钮单击:带有单击 XHR 条件的 waitUntil()?

Mur*_*can 2 javascript xmlhttprequest wait cypress

在非常高的级别上,我们单击一个命令建筑物控制点的按钮;打开或关闭灯。单击应该向服务器发送 POST 请求。问题是有时单击按钮但 POST 请求不会发出。该按钮没有指示它是否已被单击的功能(小幅增强)。

目前,我想使用 Cypress 插件waitUntil()来解决这个问题。

    // define routes
    cy.server();
    cy.route('POST', '\*\*/pointcommands').as('sendCommand');

    // setup checkFunction for cy.waitUntil()
    const waitForPost200 = () => cy.wait('@sendCommand', {timeout: 10000}).then(xhr => cy.wrap(xhr).its('status').should('eq', 200));

    // setup jQuery for cy.pipe()
    const click = $el => $el.click();

    // click the button
    cy.get('.marengo-ok')
      .should('be.visible')
      .pipe(click);
      // need to pass in a synchronous should() check so that the click is retried. How can we achieve this with waitUntil ?

    // wait until checkFunction waitForPost200() returns truthy
    cy.waitUntil( (): any => waitForPost200(), {
      timeout: 10000,
      interval: 1000,
      errorMsg: 'POST not sent `enter code here`within time limit'
    });
Run Code Online (Sandbox Code Playgroud)

小智 5

我认为根本问题是测试运行者在附加事件侦听器之前单击按钮。请参阅https://www.cypress.io/blog/2019/01/22/when-can-the-test-click/中的讨论我的建议(除了使用waitUntil插件之外)是使用https://github。 com/NicholasBoll/cypress-pipe提供cy.pipe使用 jQuery 方法单击按钮

// cypress-pipe does not retry any Cypress commands
// so we need to click on the element using
// jQuery method "$el.click()" and not "cy.click()"
const click = $el => $el.click()

cy.get('.owl-dt-popup')
  .should('be.visible')
  .contains('.owl-dt-calendar-cell-content', dayRegex)
  .pipe(click)
  .should($el => {
    expect($el).to.not.be.visible
  })
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述