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()orwindow.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
localStoragebeforecy.visit()withoutonBeforeLoadcan 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
localStorageor cookies insideonBeforeLoad. - 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.