0
0
CypressHow-ToBeginner ยท 4 min read

How to Test Login in Cypress: Simple Guide with Example

To test login in Cypress, use cy.visit() to open the login page, cy.get() to find input fields, type() to enter credentials, and click() to submit the form. Then, use assertions like should() to verify successful login by checking URL or page content.
๐Ÿ“

Syntax

This is the basic syntax to test login in Cypress:

  • cy.visit(url): Opens the login page.
  • cy.get(selector): Finds an element by CSS selector.
  • type(text): Types text into an input field.
  • click(): Clicks a button or link.
  • should(assertion): Checks if an element meets a condition.
javascript
cy.visit('/login')
cy.get('input[name="username"]').type('myUser')
cy.get('input[name="password"]').type('myPass')
cy.get('button[type="submit"]').click()
cy.url().should('include', '/dashboard')
๐Ÿ’ป

Example

This example shows a complete test that visits the login page, enters username and password, submits the form, and verifies the user is redirected to the dashboard.

javascript
describe('Login Test', () => {
  it('logs in successfully with valid credentials', () => {
    cy.visit('/login')
    cy.get('input[name="username"]').type('testuser')
    cy.get('input[name="password"]').type('password123')
    cy.get('button[type="submit"]').click()
    cy.url().should('include', '/dashboard')
    cy.contains('Welcome, testuser').should('be.visible')
  })
})
Output
Test passes if URL includes '/dashboard' and welcome message is visible.
โš ๏ธ

Common Pitfalls

Common mistakes when testing login in Cypress include:

  • Using incorrect selectors that do not match the page elements.
  • Not waiting for page loads or redirects before asserting.
  • Hardcoding credentials instead of using environment variables.
  • Not clearing cookies or local storage between tests, causing state issues.

Always use reliable selectors and add assertions to confirm page state after login.

javascript
/* Wrong: Using vague selector and no wait */
cy.get('button').click()
cy.url().should('include', '/dashboard')

/* Right: Use specific selector and confirm page content */
cy.get('button[type="submit"]').click()
cy.url().should('include', '/dashboard')
cy.contains('Welcome').should('be.visible')
๐Ÿ“Š

Quick Reference

CommandPurpose
cy.visit(url)Open the login page URL
cy.get(selector)Find input fields or buttons
type(text)Enter username or password
click()Submit the login form
should('include', text)Assert URL or text content
contains(text)Check visible text on page
โœ…

Key Takeaways

Use precise selectors to target login form elements.
Always assert page URL or visible content after login.
Avoid hardcoding credentials; use environment variables.
Clear cookies or local storage between tests to avoid state issues.
Wait for page navigation or elements before asserting.