When using Cypress for automated testing, clicking links on a page is a very common operation. Cypress provides multiple methods to locate and interact with elements. Below are the steps and examples for clicking links on a page with Cypress:
1. Determine the Selector for the Link
Before clicking a link, you first need to determine the selector for the link. You can select it based on the link's text, class, ID, or other attributes. For example, suppose we have a link with the text 'More Information':
html<a href="/more-info">More Information</a>
2. Use cy.get() or cy.contains() to Locate Elements
Cypress provides multiple methods to retrieve page elements, with cy.get() and cy.contains() being the most commonly used.
- Using
cy.get()to Locate: Use it when you know the element's class name, ID, or other attributes.javascript
cy.get('a[href="/more-info"]').click();
shell- **Using `cy.contains()` to Locate**: Use it when you need to locate based on the element's text content. ```javascript cy.contains('More Information').click();
3. Click the Link
Once successfully located, use the .click() method to simulate the user's click operation.
Example Code
Suppose our page has multiple links, and we need to click the link with the text 'More Information'. Below is a complete test case:
javascriptdescribe('Link Click Test', () => { it('Clicks the "More Information" link', () => { // Visit the test page cy.visit('http://example.com'); // Locate and click the link cy.contains('More Information').click(); // Verify that navigation to the link's href target page was successful cy.url().should('include', '/more-info'); }); });
Note
- Ensure the page is fully loaded before clicking the link; otherwise, it may cause elements to not be present in the DOM yet.
- When using the
.click()method, Cypress automatically waits for the element to become clickable. If the element is obscured or not clickable, Cypress will throw an error.
Using these methods and steps, you can easily simulate click operations when using Cypress for automated testing.