0
0
CypressHow-ToBeginner ยท 4 min read

How to Use API for Login in Cypress Testing

Use cy.request() to send a login API call in Cypress, then save the authentication token or cookies for later use. This avoids UI login steps and speeds up tests by directly authenticating via API.
๐Ÿ“

Syntax

The basic syntax to perform a login via API in Cypress uses cy.request() to send HTTP requests. You specify the method, URL, and body with login credentials. Then you handle the response to store tokens or cookies for authenticated sessions.

  • method: HTTP method like POST for login.
  • url: API endpoint for login.
  • body: JSON object with username and password.
  • then(): Callback to process the response.
javascript
cy.request({
  method: 'POST',
  url: '/api/login',
  body: {
    username: 'user',
    password: 'pass'
  }
}).then((response) => {
  // Save token or cookie here
});
๐Ÿ’ป

Example

This example shows how to login via API, save the token in local storage, and then visit a protected page using Cypress.

javascript
describe('API Login Test', () => {
  it('logs in using API 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');
      // Save token to localStorage
      window.localStorage.setItem('authToken', response.body.token);
    });

    // Visit dashboard page after login
    cy.visit('/dashboard');

    // Verify dashboard content
    cy.contains('Welcome, testuser').should('be.visible');
  });
});
Output
Test passes if login API returns 200 and dashboard page shows welcome message.
โš ๏ธ

Common Pitfalls

Common mistakes when using API login in Cypress include:

  • Not waiting for cy.request() to finish before visiting pages.
  • Failing to save authentication tokens or cookies properly.
  • Using UI login steps after API login, which wastes time.
  • Hardcoding credentials instead of using environment variables.

Always ensure the token or cookie is set before navigating to protected routes.

javascript
/* Wrong way: Visiting page before login request finishes */
cy.visit('/dashboard');
cy.request({ method: 'POST', url: '/api/login', body: { username: 'user', password: 'pass' } });

/* Right way: Chain request then visit */
cy.request({ method: 'POST', url: '/api/login', body: { username: 'user', password: 'pass' } }).then(() => {
  cy.visit('/dashboard');
});
๐Ÿ“Š

Quick Reference

  • Use cy.request() with POST method to login via API.
  • Save tokens or cookies from response for session management.
  • Chain then() to wait for login completion before visiting pages.
  • Use environment variables for credentials to keep tests secure.
โœ…

Key Takeaways

Use cy.request() to perform login via API for faster tests.
Always wait for the login request to complete before visiting protected pages.
Save authentication tokens or cookies from the API response to maintain session.
Avoid UI login steps after API login to save test execution time.
Use environment variables for credentials to keep tests secure and flexible.