Consider the following HTML and Cypress test code. What text will the assertion check?
<ul> <li>Item 1</li> <li class="selected">Item 2</li> <li>Item 3</li> </ul> // Cypress test snippet cy.get('li.selected').prev().should('have.text', 'Item 1');
Remember, cy.prev() selects the immediate previous sibling element.
The element with class selected is the second li. Its previous sibling is the first li with text 'Item 1'. So the assertion checks for 'Item 1' and passes.
Given this HTML snippet, what element will cy.get('.active').next() select?
<div> <button>Save</button> <button class="active">Cancel</button> <button>Delete</button> </div>
cy.next() selects the immediate next sibling element.
The button with class active is the second button. Its next sibling is the third button with text 'Delete'.
You want to check that the previous sibling of an element with id #current has the class highlight. Which assertion is correct?
cy.get('#current').prev()
Use the assertion that checks for a CSS class on the element.
have.class checks if the element has the specified class. have.attr checks for exact attribute value, which may fail if multiple classes exist. contain.text and have.text check text content, not classes.
Given this HTML and test code, why does the test fail?
<ul> <li>First</li> <li>Second</li> <li>Third</li> </ul> // Test code cy.get('li').last().next().should('exist');
Think about what happens when you call next() on the last sibling element.
The last li has no next sibling, so cy.next() returns an empty set. The assertion should('exist') fails because no element is found.
cy.prev() behave with non-element siblings?In Cypress, if an element has a previous sibling that is a text node (like whitespace or newline), what does cy.prev() select?
Think about how Cypress interacts with the DOM elements versus text nodes.
Cypress prev() only selects element nodes, skipping text nodes like whitespace or newlines. It finds the closest previous sibling that is an element.