Cypress is an open-source website testing tool that is used to automate tests for JavaScript web applications. It is designed for end-to-end testing and it can be used for unit tests and integration tests as well. It is fast, reliable, and can run in real-time directly in the browser.
It’s built to work with any front-end framework or website, including React, Angular, and Vue. In this article, we will learn about Fixtures in Cypress.
Table of Content
What is Cypress Fixtures?
Fixtures in Cypress are used to load a fixed set of data that can be used for testing purposes. These data sets are stored in JSON files and can be easily accessed in your test cases. To directly access the fixtures data file you can put the data sets file inside 'cypress/fixtures/' folder or else you have to set the fixturesFolder path in configuration.
Syntax of Cypress Fixtures
cy.fixture(filePath, encoding, options)In this syntax:
- filePath: here, you have give a file path, If you have put the file inside cypress/fixtures folder then you can directly access the file by it's name. It is typically used to manage and access static data in your tests.
- encoding (optional): It is used to define which encoding to be used when reading the file. default encoding is utf-8. If your file uses a different encoding such as ascii, base64 then you can specify it using this parameter.
- options (optional): It is used to change the default behavior of fixture function. It include various properties such as { timeout: 60000 } to specify a custom timeout for the operation.
Fixture with Network Requests
Using fixture with network request allow you to fetch the content from the api and use that data.
Example:
describe('API Response with Fixture', function() {
beforeEach(function() {
// Load the fixture data
cy.fixture('userData').as('userData');
});
it('should mock the API response using fixture data', function() {
// Intercept the network request and return the fixture data
cy.intercept('GET', '/api/user', { fixture: 'userData' }).as('getUser');
....using Api Data.....
......
});
});
Error Handling While Working with Fixtures
The below mentioned errors are the common errors that you may face when working with fixtures.
1. Fixture File Not Found
If a fixture file is missing or incorrectly named. Cypress will throw an error. You can catch this error by adding a catch block to handle it gracefully.
Example
beforeEach(function() {
cy.fixture('complexData').then((data) => {
this.data = data;
}).catch((err) => {
cy.log('Fixture file not found or incorrect:', err.message);
throw new Error('Fixture file is missing or incorrect');
});
});
2. Invalid JSON Format
It occurs when the fixture file contains invalid JSON. This could be due to syntax errors such as missing commas, brackets, or quotes.
Solution:
- We can use any online JSON syntax validator.
3. Undefined Fixture Data
This error will occur when trying to access a property of undefined data, usually because the fixture data wasn't loaded correctly or the "this" context is not properly bound.
Solution:
- Ensure the fixture data is correctly loaded in the beforeEach hook.
- Use regular functions (not arrow functions) to maintain the correct this context.
Best Practices for Organizing and Using Fixtures in Cypress
- Keep Fixtures Up-to-Date: Regularly replace fixtures to match any modifications in API or data structures.
- Document Your Fixtures: Provide documentation or feedback to provide an explanation for the reason and use of every fixture.
- Minimize Fixture Size: Include only important records in fixtures to hold them concise and focused.
- Use Fixtures for Consistent Test Data: Ensure consistent test data across the tests for reliability and determinism.
Installation
Before we begin make sure node.js in installed in your system. Open the Windows Command Prompt, Powershell or a similar command line tool, and type:
node -vStep 1: Create a Project Folder and move to it by using following command.
mkdir cypress cd cypressStep 2: Initialize a project and Install Cypress.
npm init -y
npm install cypress –save-dev
Step 3: After Creating a Project, Run this command to start cypress.
npx cypress openStep 4: Testing type, Configuration and creating a spec.
- Choose a E2E Testing or Component Testing, then after quick configuration choose browser.
- After that create a new spec then click on your spec name to open your spec in any IDE.
Step 5: Testing HTML File.
- Create a HTML File and open it with any live server extension.
- copy that live server file serve link, for later use.
Example of Fixture in Cypress
The below example demonstrate the Fixture in Cypress
Before we start, Create a loginData.json file inside cypress/fixtures/ folder and add the below data.
{
"incorrectUsername": "wrongUser",
"incorrectPassword": "wrongPass",
"correctUsername": "correctUser",
"correctPassword": "correctPass"
}
If you have a complex JSON structure, It will work same like accessing object keys in JavaScript.
Now Create and Run HTML File and Cypress Script:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Form</title>
</head>
<body>
<h1>Login</h1>
<form id="loginForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<br><br>
<button type="button" id="loginButton" disabled>Login</button>
</form>
<p id="errorMessage" style="display: none; color: red;">Invalid credentials</p>
<p id="welcomeMessage" style="display: none;">Welcome, <span id="user"></span>!</p>
<script>
document.getElementById('username').addEventListener('input', enableButton);
document.getElementById('password').addEventListener('input', enableButton);
function enableButton() {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
document.getElementById('loginButton').disabled = !(username && password);
}
document.getElementById('loginButton').addEventListener('click', () => {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
if (username === 'correctUser' && password === 'correctPass') {
document.getElementById('welcomeMessage').style.display = 'block';
document.getElementById('user').textContent = username;
document.getElementById('errorMessage').style.display = 'none';
} else {
document.getElementById('errorMessage').style.display = 'block';
document.getElementById('welcomeMessage').style.display = 'none';
}
});
</script>
</body>
</html>
// gfg.cy.js
describe('Login Form Functionality', function (){
beforeEach(function(){
cy.fixture('loginData.json').then((data) => {
this.data = data;
});
});
it('should verify the login form elements and functionality', function(){
// 1. Visit the login page
cy.visit('http://127.0.0.1:5500/index.html');
// 2. Verify the presence and visibility of the login form elements
cy.get('#username').should('exist').and('be.visible');
cy.get('#password').should('exist').and('be.visible');
cy.get('#loginButton').should('exist').and('be.visible');
// 3. Verify that the login button is initially disabled
cy.get('#loginButton').should('be.disabled');
// 4. Enter an incorrect username and password
cy.get('#username').type(this.data.incorrectUsername);
cy.get('#password').type(this.data.incorrectPassword);
cy.get('#loginButton').should('be.enabled').click();
// 5. Verify error message is displayed
cy.get('#errorMessage').should('exist').and('be.visible').and('contain', 'Invalid credentials');
// 6. Enter a correct username and password
cy.get('#username').clear().type(this.data.correctUsername);
cy.get('#password').clear().type(this.data.correctPassword);
cy.get('#loginButton').click();
// 7. Verify the welcome message is displayed and contains the correct username
cy.get('#welcomeMessage').should('exist').and('be.visible').and('contain', `Welcome, ${this.data.correctUsername}`);
cy.get('#errorMessage').should('not.be.visible');
});
});
Output
Conclusion
Cypress is a end-to-end automated testing tool that enables efficient and reliable testing of web applications. It provides Fixtures to Load the fix data sets. By following this article, you can learn to load fix data sets in test script. Cypress commands are easy-to-write that make it an ideal choice for automating the testing of web components.