Cypress - How To Wait For Second Of Two Elements To Appear?
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('[d
Solution 1:
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}')
Demo
/// <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)
})
Post a Comment for "Cypress - How To Wait For Second Of Two Elements To Appear?"