0
0
Cypresstesting~5 mins

Dynamic test data generation in Cypress

Choose your learning style9 modes available
Introduction

Dynamic test data generation helps create fresh and unique data for each test run. This avoids conflicts and makes tests more reliable.

When testing user registration forms that require unique emails.
When filling out forms that need random but valid input values.
When you want to avoid using the same data repeatedly to catch hidden bugs.
When testing APIs that require unique identifiers or tokens.
When simulating real user behavior with varied inputs.
Syntax
Cypress
const randomValue = Math.random().toString(36).substring(2, 10);
const testEmail = `user_${randomValue}@example.com`;
Use JavaScript's Math.random() to create random strings.
Combine random parts with fixed strings to form valid test data like emails.
Examples
This creates a username like 'user123' with a random number between 0 and 999.
Cypress
const randomNumber = Math.floor(Math.random() * 1000);
const username = `user${randomNumber}`;
This uses the current time in milliseconds to generate a unique email each time.
Cypress
const randomEmail = `test_${Date.now()}@mail.com`;
This generates a password with a random string inside for uniqueness.
Cypress
const randomString = Math.random().toString(36).slice(2, 8);
const password = `Pass!${randomString}123`;
Sample Program

This Cypress test visits a registration page, fills in a unique email generated dynamically, enters a password, submits the form, and checks for a success message.

Cypress
describe('User Registration with Dynamic Data', () => {
  it('should register a user with a unique email', () => {
    const randomValue = Math.random().toString(36).substring(2, 10);
    const email = `user_${randomValue}@example.com`;
    const password = 'Test@1234';

    cy.visit('https://example.com/register');
    cy.get('input[name="email"]').type(email);
    cy.get('input[name="password"]').type(password);
    cy.get('button[type="submit"]').click();

    cy.contains('Registration successful').should('be.visible');
  });
});
OutputSuccess
Important Notes

Always ensure generated data matches the format expected by the application.

Use dynamic data to avoid test flakiness caused by duplicate entries.

Keep generated data simple and readable for easier debugging.

Summary

Dynamic test data helps tests run independently without conflicts.

Use JavaScript functions like Math.random() and Date.now() to create unique values.

Apply dynamic data in form inputs, API calls, and anywhere unique data is needed.