赛普拉斯-如何等待两个元素中的第二个出现? [英] Cypress - how to wait for second of two elements to appear?

查看:46
本文介绍了赛普拉斯-如何等待两个元素中的第二个出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想等到两个元素中的第二个出现后再对其执行操作.目前,我有这个:

I want to wait until the second of two elements to appear before performing an action on it. Currently, I have this:

    cy.get('[data-test="insert-item"]').click();
    cy.get('[data-test="textarea"]').eq(1).type('Hello').type('{enter}');

当前失败.我假设这是因为赛普拉斯将收集所有出现的 textarea ,然后尝试选择第二个在它实际呈现在页面上之前(因为创建它的异步请求).如果我在这两行之间添加 cy.wait(2000); ,则会通过.

This currently fails. I'm assuming this is because Cypress is going to collect all the occurrences of textarea, then try to select the second one before it has actually rendered on the page (because of the async request that creates it). If I add cy.wait(2000); in between these two lines it passes.

是否可以使用不使用 cy.wait(2000)的方法来执行此操作,以便它专门等到第二项出现为止?

Is there any way to do this without using cy.wait(2000), so that it specifically waits until the second item has appeared?

推荐答案

您可以使用:nth(1) eq()移到选择器中,这将导致索引成为 cy.get()重试机制的一部分

You can move the eq() into the selector with :nth(1), which will cause the indexing to be part of the cy.get() retry mechanism

cy.get('[data-test="textarea"]:nth(1)')
  .type('Hello').type('{enter}')

或者您可以在索引列表之前声明所选元素的长度.

Or you can assert the length of the elements selected before indexing the list.

cy.get('[data-test="textarea"]')
  .should('have.length', 2)
  .eq(1)
  .type('Hello').type('{enter}')


演示

/// <reference types="@cypress/fiddle" />

const waitForAdd = {
  html: `
    <div id="parent">
      <textarea data-test="textarea">1</textarea>
      <button data-test="insert-item" onclick = "myFunction()"></button>
    </div>
    <script>
      const myFunction = () => {
        setTimeout(() => {
          const parent = document.querySelector('div#parent');
          let ta = document.createElement("textarea");
          ta.setAttribute('data-test', 'textarea');
          parent.appendChild(ta);
        }, 500)
      }
    </script>
  `,
  test: `
    cy.get('[data-test="insert-item"]').click();
    cy.get('[data-test="textarea"]:nth(1)')
      .type('Hello').type('{enter}')
    cy.get('[data-test="textarea"]:nth(1)')
      .invoke('val')
      .should('eq', 'Hello\\n')

    cy.get('[data-test="insert-item"]').click();
    cy.get('[data-test="textarea"]')
      .should('have.length', 3)
      .eq(2)
      .type('Hello again').type('{enter}')
    cy.get('[data-test="textarea"]')
      .eq(2)
      .invoke('val')
      .should('eq', 'Hello again\\n')
`
}
it('tests hello', () => {
  cy.runExample(waitForAdd)
})

这篇关于赛普拉斯-如何等待两个元素中的第二个出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆