Mock API response using fixture in Cypress
Preconditions (3)
✅ Expected Result: The UI shows user information exactly as defined in the 'user.json' fixture file, confirming the API response was mocked successfully.
describe('Fixture-based response mocking test', () => { beforeEach(() => { cy.intercept('GET', '/api/user', { fixture: 'user.json' }).as('getUser'); cy.visit('/user-profile'); }); it('should display user data from fixture', () => { cy.wait('@getUser'); cy.fixture('user.json').then((user) => { cy.get('[data-cy=user-name]').should('contain.text', user.name); cy.get('[data-cy=user-email]').should('contain.text', user.email); }); }); });
This test uses cy.intercept() to mock the GET request to /api/user with the fixture user.json. The as('getUser') creates an alias to wait for the request to complete. The test visits the user profile page, waits for the mocked API call, then loads the fixture data again to assert that the UI elements display the expected user name and email. Using data-cy attributes for selectors follows best practices for stable tests.
Now add data-driven testing with 3 different user fixtures to verify the UI displays each user's data correctly
cy.intercept('GET', '/api/products', { fixture: 'products.json' })
cy.visit('/products')
Assume 'products.json' contains [{"id":1,"name":"Book"}].cy.intercept('POST', '/api/users', { fixture: 'newUser.json' })
cy.visit('/users')Pass the test and this pattern moves unknown