0
0
Cypresstesting~15 mins

JSON fixture files in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify user login using JSON fixture data
Preconditions (2)
Step 1: Open the login page at 'https://example.com/login'.
Step 2: Load the 'user.json' fixture file containing username and password.
Step 3: Enter the username from the fixture into the username input field with id 'username'.
Step 4: Enter the password from the fixture into the password input field with id 'password'.
Step 5: Click the login button with id 'loginBtn'.
Step 6: Verify that the URL changes to 'https://example.com/dashboard'.
Step 7: Verify that a welcome message with id 'welcomeMsg' contains the username from the fixture.
✅ Expected Result: User is successfully logged in and redirected to the dashboard page with a welcome message showing the username.
Automation Requirements - Cypress
Assertions Needed:
URL should be 'https://example.com/dashboard' after login
Welcome message should contain the username from the fixture
Best Practices:
Use cy.fixture() to load JSON data
Use data-driven selectors with IDs
Use explicit assertions with should()
Avoid hardcoding credentials in test code
Automated Solution
Cypress
describe('Login Test with JSON Fixture', () => {
  beforeEach(() => {
    cy.visit('https://example.com/login');
  });

  it('logs in using credentials from fixture', () => {
    cy.fixture('user.json').then((user) => {
      cy.get('#username').type(user.username);
      cy.get('#password').type(user.password);
      cy.get('#loginBtn').click();

      cy.url().should('eq', 'https://example.com/dashboard');
      cy.get('#welcomeMsg').should('contain.text', user.username);
    });
  });
});

This test uses Cypress to automate login using data from a JSON fixture file named user.json. The beforeEach hook opens the login page before each test. Inside the test, cy.fixture('user.json') loads the JSON data asynchronously. Then, it types the username and password into the input fields identified by their IDs. After clicking the login button, the test asserts that the URL is the dashboard URL and that the welcome message contains the username from the fixture. This approach keeps test data separate from test code, making tests easier to maintain and more secure.

Common Mistakes - 3 Pitfalls
Hardcoding username and password directly in the test code
Using CSS selectors that are brittle or too generic instead of stable IDs
Not waiting for the fixture to load before using its data
Bonus Challenge

Now add data-driven testing with 3 different user credentials stored in the JSON fixture file.

Show Hint