0
0
Cypresstesting~15 mins

Programmatic login (cy.request) in Cypress - Build an Automation Script

Choose your learning style9 modes available
Programmatic login using cy.request in Cypress
Preconditions (3)
Step 1: Send a POST request to '/api/login' with JSON body containing username 'testuser' and password 'Test@1234'
Step 2: Verify the response status code is 200
Step 3: Extract the authentication token from the response body
Step 4: Set the authentication token in local storage or cookies as required by the application
Step 5: Visit the '/dashboard' page
Step 6: Verify that the dashboard page loads successfully by checking the URL and presence of a welcome message
✅ Expected Result: User is logged in programmatically and dashboard page is displayed with a welcome message
Automation Requirements - Cypress
Assertions Needed:
Response status code is 200
Authentication token exists in response body
URL after visiting dashboard is '/dashboard'
Dashboard contains a visible welcome message element
Best Practices:
Use cy.request for API login instead of UI login to speed up tests
Use explicit assertions on response and page elements
Avoid hardcoding selectors; use data-cy attributes if available
Handle authentication token securely and set it properly before visiting pages
Use beforeEach hook to perform login if multiple tests require authentication
Automated Solution
Cypress
describe('Programmatic login using cy.request', () => {
  it('logs in via API and visits dashboard', () => {
    cy.request({
      method: 'POST',
      url: '/api/login',
      body: {
        username: 'testuser',
        password: 'Test@1234'
      }
    }).then((response) => {
      expect(response.status).to.equal(200);
      expect(response.body).to.have.property('token');
      const token = response.body.token;
      // Set token in local storage
      window.localStorage.setItem('authToken', token);
      // Now visit dashboard
      cy.visit('/dashboard');
      // Verify URL
      cy.url().should('include', '/dashboard');
      // Verify welcome message is visible
      cy.get('[data-cy=welcome-message]').should('be.visible');
    });
  });
});

This test uses cy.request to send a POST request to the login API with the username and password. It then asserts the response status is 200 and that the response body contains a token. The token is saved to local storage to simulate a logged-in state. After setting the token, the test visits the dashboard page and verifies the URL and the presence of a welcome message element. This approach avoids using the UI login form, making tests faster and more reliable.

Selectors use data-cy attributes for stability. Assertions ensure the login succeeded and the dashboard loaded correctly.

Common Mistakes - 4 Pitfalls
Using cy.visit to load the login page and typing credentials instead of cy.request
Not asserting the response status or token existence after cy.request
Setting authentication token incorrectly or after visiting the page
Using brittle selectors like classes or IDs that may change
Bonus Challenge

Now add data-driven testing with 3 different sets of valid login credentials

Show Hint