cypress-test-data-generator
v2.0.2
Published
Cypress plugin for generating test data using Faker
Maintainers
Readme
Cypress Test Data Generator
Generate realistic, reproducible test data for Cypress tests
Installation • Quick Start • Generators • Examples • API • Contributing
Why This Plugin?
Writing realistic test data by hand is tedious and error-prone. This plugin provides 40+ data generators powered by Faker.js that create consistent, realistic data for your Cypress tests.
// Before: Manual test data
const user = { name: 'Test User', email: '[email protected]', age: 25 };
// After: Rich, realistic data
cy.task('generateUser').then((user) => {
// { id, firstName, lastName, email, phone, avatar, dateOfBirth, address, preferences, ... }
});Key Features
- 40+ Generators — Users, products, orders, invoices, social profiles, and more
- Reproducible Data — Seed support for consistent test runs
- Internationalization — 50+ locales for localized data
- Zero Config — Works out of the box with sensible defaults
- Fully Typed — Consistent API across all generators
Installation
npm install --save-dev cypress-test-data-generatorSetup
Add the plugin to your cypress.config.js:
const { defineConfig } = require('cypress');
const dataGenerator = require('cypress-test-data-generator');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
on('task', dataGenerator(on, config));
},
},
});Quick Start
// Generate a single user
cy.task('generateUser').then((user) => {
cy.visit('/register');
cy.get('#email').type(user.email);
cy.get('#name').type(`${user.firstName} ${user.lastName}`);
});
// Generate with options
cy.task('generateUser', {
seed: 12345, // Same seed = same data
locale: 'de' // German names/addresses
});
// Generate related data
cy.task('generateProduct').then((product) => {
cy.task('generateReview', { productId: product.id }).then((review) => {
// Test product with its review
});
});Available Generators
| Generator | Description |
|-----------|-------------|
| generateUser | Complete user profile with address and preferences |
| generateAddress | Standalone address with coordinates |
| Generator | Description |
|-----------|-------------|
| generateProduct | Product with SKU, pricing, stock status |
| generateProductWithRelations | Product with related products |
| generateOrder | Order with products and shipping |
| generateReview | Product review with rating |
| generateCategory | Category with hierarchy support |
| generateCart | Shopping cart with items |
| generateWishlist | User wishlist |
| generateReturn | Return/refund request |
| generateInventory | Product inventory |
| generateCoupon | Discount coupon |
| generateShippingMethod | Shipping option |
| generatePaymentMethod | Payment method |
| Generator | Description |
|-----------|-------------|
| generateSocialProfile | Social media profile (Twitter, Instagram, etc.) |
| generateComment | Comment with replies support |
| generateNotification | App notification |
| generateMessage | Chat/direct message |
| Generator | Description |
|-----------|-------------|
| generateCompany | Company with industry and revenue |
| generateInvoice | Invoice with line items |
| generateEmployee | Employee with department and salary |
| generateProject | Project with team and milestones |
| generateTicket | Support ticket |
| generateMeeting | Meeting with attendees |
| generateJobListing | Job posting |
| Generator | Description |
|-----------|-------------|
| generateBankAccount | Bank account with balance |
| generateLoan | Loan with terms and payments |
| generateInsurancePolicy | Insurance policy |
| generateCreditCard | Credit card details |
| generateTransaction | Financial transaction |
| generateSubscription | Subscription plan |
| Generator | Description |
|-----------|-------------|
| generateBlogPost | Blog post with SEO metadata |
| generateEvent | Event with tickets and speakers |
| Generator | Description |
|-----------|-------------|
| generateTravelItinerary | Travel plan with flights and hotels |
| generateVehicle | Vehicle with specifications |
| Generator | Description |
|-----------|-------------|
| generateProperty | Property listing with agent info |
| Generator | Description |
|-----------|-------------|
| generateRestaurant | Restaurant with hours and features |
| generateMenuItem | Menu item with nutrition info |
| generateFoodOrder | Food delivery order |
| Generator | Description |
|-----------|-------------|
| generateApiResponse | API response with pagination |
| generateLogEntry | Application log entry |
| Generator | Description |
|-----------|-------------|
| generateMedicalRecord | Medical record |
| generateEducation | Education record |
Usage Examples
E-commerce Testing
describe('Shopping Flow', () => {
it('completes checkout with generated data', () => {
cy.task('generateProduct').then((product) => {
cy.task('generateCart', { itemCount: 3 }).then((cart) => {
cy.task('generateUser').then((user) => {
// Use generated data in your test
expect(cart.items).to.have.length(3);
expect(cart.total).to.be.greaterThan(0);
});
});
});
});
it('displays order history', () => {
cy.task('generateOrder', { productCount: 5 }).then((order) => {
expect(order.products).to.have.length(5);
expect(order.totalAmount).to.equal(
order.products.reduce((sum, p) => sum + p.price, 0)
);
});
});
});Business Application Testing
describe('Invoice Management', () => {
it('creates invoice with line items', () => {
cy.task('generateInvoice', { itemCount: 5 }).then((invoice) => {
expect(invoice.invoiceNumber).to.match(/^INV-\d{6}$/);
expect(invoice.items).to.have.length(5);
expect(invoice.total).to.be.greaterThan(invoice.subtotal); // Includes tax
});
});
});
describe('Employee Directory', () => {
it('filters by department', () => {
cy.task('generateEmployee', { department: 'Engineering' }).then((emp) => {
expect(emp.department).to.equal('Engineering');
expect(emp.employeeId).to.match(/^EMP-\d{6}$/);
});
});
});Social Features Testing
describe('Social Feed', () => {
it('displays user notifications', () => {
cy.task('generateNotification', { type: 'payment' }).then((notif) => {
expect(notif.type).to.equal('payment');
expect(notif.priority).to.be.oneOf(['low', 'medium', 'high', 'urgent']);
});
});
it('shows social profile', () => {
cy.task('generateSocialProfile', { platform: 'instagram' }).then((profile) => {
expect(profile.platform).to.equal('instagram');
expect(profile.followers).to.be.a('number');
expect(profile.isVerified).to.be.a('boolean');
});
});
});Common Options
All generators accept these common options:
| Option | Type | Description |
|--------|------|-------------|
| seed | number | Seed for reproducible data generation |
| locale | string | Locale code (en, de, fr, es, etc.) |
Reproducible Tests with Seeds
const seed = 12345;
// These will always generate identical data
cy.task('generateUser', { seed }).then((user1) => {
cy.task('generateUser', { seed }).then((user2) => {
expect(user1.email).to.equal(user2.email);
expect(user1.firstName).to.equal(user2.firstName);
});
});Localized Data
// German names and addresses
cy.task('generateUser', { locale: 'de' }).then((user) => {
// User with German-style data
});
// French company
cy.task('generateCompany', { locale: 'fr' }).then((company) => {
// Company with French-style data
});Schema Validators
The plugin includes reusable schema validators for cleaner tests:
import { expectValidUser, expectValidProduct, expectValidOrder } from '../support/schemas';
describe('Data Generation', () => {
it('generates valid user', () => {
cy.task('generateUser').then(expectValidUser);
});
it('generates valid product', () => {
cy.task('generateProduct').then(expectValidProduct);
});
it('generates valid order', () => {
cy.task('generateOrder').then(expectValidOrder);
});
});Error Handling
The plugin provides descriptive errors for invalid inputs:
// Invalid age range
cy.task('generateUser', { ageMin: 50, ageMax: 30 }).then((result) => {
// Returns: { error: 'Max 30 should be greater than min 50' }
});Requirements
| Dependency | Version | |------------|---------| | Cypress | 13.0.0+ | | Node.js | 18+ |
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT License - see the LICENSE file for details.
Made with 🔧 by Ahmad Waqar
