How to Use Cypress in a Web Project
How to Test Buttons and Links with Cypress
Cypress is a powerful testing framework used for end-to-end testing in web applications. It's known for being fast, reliable, and developer-friendly.
In this guide, we’ll focus on testing two key UI elements:
-
Buttons
-
Links
Let’s break it down step by step.
๐งช Why Test Buttons and Links?
Buttons and links are essential parts of any user interface. You want to make sure:
-
They are visible and clickable
-
They navigate correctly
-
They trigger the right actions
-
They handle errors or loading states
Cypress makes it easy to automate and repeat these tests.
๐ Setting Up Cypress
Before writing tests, make sure Cypress is installed:
To open Cypress test runner:
Create your test file in:
๐ 1. How to Test a Button
✅ Basic Button Test
Explanation:
-
cy.visit()
opens your app -
cy.contains()
finds the button by text -
should('be.visible')
checks visibility -
.click()
performs a click
✅ Button with ID
Finds a button with id="loginBtn"
and clicks it.
✅ Button with Class
Checks if button is enabled and clicks it.
✅ Check Button Action
After clicking the button, check if success message appears.
✅ Disabled Button
Confirms button is not clickable.
๐ 2. How to Test a Link
✅ Check Link Text and Navigation
-
cy.contains('About')
finds the link -
.click()
simulates user click -
cy.url()
checks if the URL changed
✅ Link with Specific Selector
Confirms correct link path and navigation.
✅ External Link (opens in new tab)
Note: Cypress doesn’t support new tabs, but you can test the link target and href.
๐งช Combine Button and Link Tests
Example: Login and Redirect
Tests:
-
Button click triggers login
-
Redirects to the dashboard
-
Shows welcome text
๐ Waiting for Actions
Sometimes the page needs time to update. Use .should()
or .wait()
:
⚠️ Testing Edge Cases
❌ Button Click with No Action
Make sure user errors are shown when expected.
๐ Link that Refreshes or Reloads Page
Test links that reload the same route.
๐ Organize Tests in Folders
Structure:
Use describe()
blocks to group tests clearly.
⏳ Handling Slow Responses
Use timeouts if needed:
Waits up to 10 seconds before failing.
✅ Final Checklist
Test Action | Cypress Command Example |
---|---|
Check if button is visible | cy.get('#btn').should('be.visible') |
Click a button | cy.get('#btn').click() |
Check link destination | cy.get('a').should('have.attr', 'href') |
Confirm redirection | cy.url().should('include', '/path') |
Validate after-click message | cy.contains('Success') |
Test external link | cy.get('a[target="_blank"]') |
๐ Conclusion
Testing buttons and links with Cypress is simple and powerful:
-
Use
cy.get()
orcy.contains()
to locate elements -
Use
.click()
to simulate user actions -
Use
.should()
to check visibility, URLs, and results
Well-tested buttons and links create a smoother, error-free user experience.
Comments
Post a Comment