0
0
CypressHow-ToBeginner ยท 3 min read

How to Bypass Login in Cypress for Faster Tests

To bypass login in Cypress, use cy.request() to programmatically authenticate and set the session or token directly in localStorage or cookies before visiting the app. This skips the UI login flow and speeds up tests.
๐Ÿ“

Syntax

Use cy.request() to send a login API call, then save the authentication token or session data using cy.setCookie() or window.localStorage. Finally, visit the app page with cy.visit().

  • cy.request(): Sends HTTP request to login endpoint.
  • cy.setCookie() or window.localStorage.setItem(): Stores auth info.
  • cy.visit(): Opens the app page as logged in user.
javascript
cy.request('POST', '/api/login', { username: 'user', password: 'pass' })
  .then((response) => {
    window.localStorage.setItem('authToken', response.body.token)
  })
cy.visit('/dashboard')
๐Ÿ’ป

Example

This example shows how to bypass login by calling the login API, saving the token in localStorage, and then visiting the dashboard page directly.

javascript
describe('Bypass Login Test', () => {
  it('logs in without UI', () => {
    cy.request('POST', '/api/login', { username: 'testuser', password: 'testpass' })
      .then((response) => {
        expect(response.status).to.eq(200)
        window.localStorage.setItem('authToken', response.body.token)
      })
    cy.visit('/dashboard')
    cy.contains('Welcome, testuser').should('be.visible')
  })
})
Output
Test passes if the dashboard loads and 'Welcome, testuser' is visible.
โš ๏ธ

Common Pitfalls

  • Trying to set localStorage before cy.visit() without onBeforeLoad can fail because the page context is not ready.
  • Not waiting for cy.request() to finish before visiting the page causes flaky tests.
  • Hardcoding credentials in tests is insecure; use environment variables.
javascript
/* Wrong way: setting localStorage outside visit */
window.localStorage.setItem('authToken', 'token')
cy.visit('/dashboard')

/* Right way: set localStorage inside onBeforeLoad */
cy.visit('/dashboard', {
  onBeforeLoad(win) {
    win.localStorage.setItem('authToken', 'token')
  }
})
๐Ÿ“Š

Quick Reference

Tips to bypass login in Cypress:

  • Use cy.request() to authenticate via API.
  • Set auth tokens in localStorage or cookies inside onBeforeLoad.
  • Visit the protected page after setting auth data.
  • Use environment variables for credentials.
โœ…

Key Takeaways

Use cy.request() to authenticate via API and get tokens.
Set authentication tokens in localStorage or cookies inside cy.visit() onBeforeLoad callback.
Avoid UI login steps to speed up tests and reduce flakiness.
Always wait for cy.request() to complete before visiting pages.
Keep credentials secure using environment variables.