How to Use JSON Files for Mocking Data in Cypress
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:
// 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', () => {
console.log(user);
});
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.
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:
Resources:
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: