Why external test data improves maintainability in Cypress - Automation Benefits in Action
/// <reference types="cypress" /> describe('Login Tests with External Data', () => { beforeEach(() => { cy.visit('https://example.com/login'); }); it('should test login with multiple credentials from external data', () => { cy.fixture('loginData.json').then((users) => { users.forEach((user) => { cy.get('#username').clear().type(user.username); cy.get('#password').clear().type(user.password); cy.get('#loginBtn').click(); if (user.expectedOutcome === 'success') { cy.url().should('include', '/dashboard'); // Logout to reset state for next iteration cy.get('#logoutBtn').click(); cy.url().should('include', '/login'); } else if (user.expectedOutcome === 'failure') { cy.get('.error-message').should('be.visible').and('contain.text', 'Invalid credentials'); } }); }); }); });
This Cypress test uses an external JSON file named loginData.json to load multiple sets of login credentials. This approach improves maintainability because test data is separated from test logic, making it easier to update or add new test cases without changing the test code.
The beforeEach hook ensures the login page is loaded before each test iteration. The test iterates over each user in the fixture data, enters the username and password, clicks the login button, and then verifies the outcome based on the expected result from the data.
Using clear selectors like #username and #loginBtn ensures the test is easy to read and maintain. Assertions check the URL for successful login or the presence of an error message for failed login.
Resetting the state by logging out after a successful login ensures each test iteration starts fresh, preventing state leakage between tests.
Now add data-driven testing with 3 different inputs including valid, invalid, and empty credentials.