How to Use JSON Files for Mocking Data in Cypress

How to Use JSON Files for Mocking Data in Cypress

Ferenc Almasi β€’ 2021 December 14 β€’ Read time 2 min read
  • twitter
  • facebook

There are several ways in Cypress to use JSON files for mocking data. Cypress uses so-called fixtures for that. By default, it will generate a fixtures folder where you can store your JSON mock files.

Accessing Fixtures

To access fixtures, you can either use cy.fixture, or simply import the file with an import statement:

Copied to clipboard! Playground
// Access contents of a fixture:
cy.fixture('user').then(data => {
    console.log('fixture is:', data);

// Load fixtures with an import:
import user from '../fixtures/user.json'

it('Should load the JSON file', () => {    

Note that when you use cy.fixture, you don't need to specify the folder (in case you use the default fixtures folder) or the extension. The above example will automatically resolve to fixtures/user.json

Mocking Network Requests

Fixtures can also be used to mock network requests, by using cy.intercept. This is useful if you want to mock the response of your API.

Copied to clipboard!
cy.intercept('/login', { fixture: 'login.json' }, request => {
    cy.url().should('include', 'dashboard');

In the code example above, if a network request is being made to /login, it will respond with the contents of login.json.

Just as for cy.fixture, you can also omit the directory name in case you use the default fixtures folder. The request that is passed to the callback will represent the intercepted request.

Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:

Learn Cypress with Educative
How to Use JSON Files for Mocking Data in Cypress
If you would like to see more webtips, follow @flowforfrank
Looking to improve your skills? Check out our interactive course to master Cypress from start to finish.
Master Cypressinfo Remove ads


  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:



This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.