Working with Data

When testing applications, working with data is crucial. Whether it's test data stored in files, dynamically generated data, or interacting with APIs, Cypress makes it easy to handle data effectively. This tutorial covers how to work with different types of data in Cypress tests.

Using Fixtures

Fixtures are files that store static test data, such as JSON, images, or text files. They are ideal for simulating user input, API responses, or any other consistent test data.

Fixture Folder

  • By default, Cypress looks for fixture files in the cypress/fixtures folder.

Create a Fixture File

Example: users.json in cypress/fixtures/:

JSON
Copy
{
  "validUser": {
    "username": "testUser",
    "password": "password123"
  },
  "invalidUser": {
    "username": "wrongUser",
    "password": "wrongPassword"
  }
}

Load Fixture Data

Use the cy.fixture() command to load data in your tests.

Example:

Javascript
Copy
it('should log in with valid credentials', () => {
  cy.fixture('users').then((data) => {
    cy.get('input[name="username"]').type(data.validUser.username);
    cy.get('input[name="password"]').type(data.validUser.password);
    cy.get('button[type="submit"]').click();
  });
});

Interacting with APIs

Cypress allows you to fetch, mock, or validate data from APIs during tests.

Fetching Data with cy.request()

You can make HTTP requests directly using cy.request().

Example: GET Request

Javascript
Copy
it('should fetch user data from the API', () => {
  cy.request('GET', '/api/users').then((response) => {
    expect(response.status).to.eq(200);
    expect(response.body).to.have.property('users');
  });
});

Example: POST Request

Javascript
Copy
it('should create a new user', () => {
  const user = { username: 'newUser', password: 'password123' };
  cy.request('POST', '/api/users', user).then((response) => {
    expect(response.status).to.eq(201);
    expect(response.body).to.have.property('id');
  });
});

Mocking API Responses

Mocking lets you simulate API responses without needing the actual backend.

Using cy.intercept()

You can intercept API calls and provide a custom response.

Example: Mock a GET Request
Javascript
Copy
cy.intercept('GET', '/api/users', {
  statusCode: 200,
  body: { users: [{ id: 1, name: 'Test User' }] }
}).as('getUsers');

cy.visit('/users');
cy.wait('@getUsers').its('response.body.users').should('have.length', 1);

Example: Mock a POST Request

Javascript
Copy
cy.intercept('POST', '/api/login', {
  statusCode: 200,
  body: { token: '12345' }
}).as('login');

Generating Dynamic Data

Dynamic data is useful when you want unique or randomized inputs, such as emails or usernames.

Using Libraries like faker.js

Install faker.js:

npm install faker --save-dev

Example: Generate Random Data

Javascript
Copy
const faker = require('faker');

it('should sign up with random user data', () => {
  const randomName = faker.name.findName();
  const randomEmail = faker.internet.email();

  cy.get('input[name="name"]').type(randomName);
  cy.get('input[name="email"]').type(randomEmail);
  cy.get('button[type="submit"]').click();
});

Working with Local Storage

Cypress allows you to read, write, and validate data in local storage.

Set Local Storage

Javascript
Copy
cy.setLocalStorage('authToken', '123456');

Get Local Storage

Javascript
Copy
cy.getLocalStorage('authToken').should('eq', '123456');

Clear Local Storage

Javascript
Copy
cy.clearLocalStorage();

Handling Cookies

Cookies are often used to store user sessions. Cypress provides commands to manage cookies.

Set a Cookie

Javascript
Copy
cy.setCookie('session_id', 'abcdef');

Get a Cookie

Javascript
Copy
cy.getCookie('session_id').should('have.property', 'value', 'abcdef');

Clear Cookies

Javascript
Copy
cy.clearCookies();

Validating Data in the UI

You can validate data displayed in the UI against expected values.

Example: Check Table Data

Javascript
Copy
cy.get('table#userTable').find('tr').should(($rows) => {
  expect($rows).to.have.length(3); // Check number of rows
  expect($rows.eq(0)).to.contain('John Doe'); // Check specific row content
});

Example: Validate Form Values

Javascript
Copy
cy.get('input[name="username"]').should('have.value', 'testUser');

Working with Files

Cypress supports file uploads and downloads.

Test File Uploads

Install the cypress-file-upload plugin:

npm install --save-dev cypress-file-upload

Enable the plugin in cypress/support/commands.js:

Javascript
Copy
import 'cypress-file-upload';

Example: Upload a File

Javascript
Copy
const filePath = 'images/testImage.png';

cy.get('input[type="file"]').attachFile(filePath);
cy.get('.upload-status').should('contain', 'Upload successful');

Test File Downloads

Use cy.intercept() to verify that the file download request succeeds.

Example:

Javascript
Copy
cy.intercept('GET', '/files/sample.pdf').as('fileDownload');
cy.get('button#download').click();
cy.wait('@fileDownload').its('response.statusCode').should('eq', 200);

Data Cleanup After Tests

To avoid test data clutter, clean up the data after each test. Use hooks like afterEach() to reset the state.

Example: Cleanup API Data

Javascript
Copy
afterEach(() => {
  cy.request('DELETE', '/api/users/cleanup');
});