Programmatic login helps you log in quickly without using the UI. It saves time and makes tests faster and more reliable.
0
0
Programmatic login (cy.request) in Cypress
Introduction
When you want to skip the login page and test features behind login.
When the login UI is slow or flaky and slows down your tests.
When you want to test multiple scenarios without repeating the login steps.
When you want to keep your tests simple and focused on the main feature.
When you want to avoid UI changes breaking your login tests.
Syntax
Cypress
cy.request({
method: 'POST',
url: '/api/login',
body: {
username: 'yourUsername',
password: 'yourPassword'
}
}).then((response) => {
// save token or cookie from response
cy.setCookie('authToken', response.body.token)
})Use cy.request to send HTTP requests directly to your backend.
After login, save the token or cookie to keep the session active for next steps.
Examples
Simple POST request with username and password, then save session cookie.
Cypress
cy.request('POST', '/api/login', { username: 'user1', password: 'pass123' }) .then((response) => { expect(response.status).to.eq(200) cy.setCookie('session_id', response.body.sessionId) })
POST request with headers and assertion on response body token.
Cypress
cy.request({
method: 'POST',
url: '/api/login',
body: { username: 'user2', password: 'pass456' },
headers: { 'Content-Type': 'application/json' }
}).then((response) => {
expect(response.body).to.have.property('token')
cy.setCookie('authToken', response.body.token)
})Sample Program
This test logs in by sending a POST request to the login API. It checks the response status and token, saves the token as a cookie, then visits the dashboard page. Finally, it checks that the welcome message is visible.
Cypress
describe('Programmatic Login Test', () => { it('logs in using cy.request and visits dashboard', () => { cy.request({ method: 'POST', url: '/api/login', body: { username: 'testuser', password: 'testpass' } }).then((response) => { expect(response.status).to.eq(200) expect(response.body).to.have.property('token') cy.setCookie('authToken', response.body.token) cy.visit('/dashboard') cy.contains('Welcome, testuser').should('be.visible') }) }) })
OutputSuccess
Important Notes
Make sure the API endpoint and request body match your backend login API.
Use cy.setCookie or localStorage to keep the login session.
Programmatic login skips UI, so test UI login separately if needed.
Summary
Programmatic login uses cy.request to log in faster without UI.
Save tokens or cookies after login to keep the session.
Use it to speed up tests and avoid flaky UI login steps.