0
0
Cypresstesting~5 mins

Fixture-based response mocking in Cypress

Choose your learning style9 modes available
Introduction

Fixture-based response mocking helps you test your app by pretending the server sends fixed data. This way, you can check how your app works without needing a real server.

When the real server is slow or not ready.
When you want to test how your app handles specific data.
When you want to avoid changing real data during tests.
When you want consistent test results every time.
When testing error or special cases that are hard to get from the real server.
Syntax
Cypress
cy.intercept('GET', '/api/data', { fixture: 'data.json' })

cy.intercept is used to catch network requests and replace their response.

The fixture option tells Cypress to use a file from the cypress/fixtures folder as the response.

Examples
This mocks a GET request to '/users' and returns data from 'users.json' fixture file.
Cypress
cy.intercept('GET', '/users', { fixture: 'users.json' })
This mocks a POST request to '/login' and returns a fixed success response from the fixture.
Cypress
cy.intercept('POST', '/login', { fixture: 'login-success.json' })
This mocks '/products' GET request and gives it an alias to wait for it later in the test.
Cypress
cy.intercept('GET', '/products', { fixture: 'products.json' }).as('getProducts')
Sample Program

This test mocks the GET request to '/api/users' with data from 'users.json'. It visits the users page, waits for the mocked request, and checks if the page shows the user name 'Alice' from the fixture.

Cypress
describe('Fixture-based response mocking example', () => {
  it('shows mocked user data', () => {
    cy.intercept('GET', '/api/users', { fixture: 'users.json' }).as('getUsers')
    cy.visit('/users-page')
    cy.wait('@getUsers')
    cy.get('.user-name').should('contain.text', 'Alice')
  })
})
OutputSuccess
Important Notes

Put your fixture files inside the cypress/fixtures folder.

Use cy.wait('@alias') to wait for the mocked request to finish before checking the page.

Fixture mocking works well for stable, repeatable tests without depending on real servers.

Summary

Fixture-based mocking replaces real server responses with fixed data files.

This helps test your app in a fast, reliable, and controlled way.

Use cy.intercept with the fixture option to mock responses easily.