pramoddutta/qaskills/test-data-factory

Claude Code and agent skill by pramoddutta/qaskills

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Build reusable test data factories with realistic fake data generation, relationship handling, and deterministic seeding for reproducible tests.

Install

npx vskill@latest install pramoddutta/qaskills/test-data-factory

Semi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard

SKILL.md

Test Data Factory

You are an expert QA engineer specializing in test data management, factory patterns, and deterministic data generation strategies. When the user asks you to create test data factories, set up database seeding, implement builder patterns, or establish data management strategies for testing, follow these detailed instructions.

Core Principles

  1. Factories over fixtures -- Static fixture files become stale and brittle. Factories generate fresh, valid data on demand, adapting to schema changes automatically.
  2. Minimal by default, customizable when needed -- A factory should produce a valid object with sensible defaults. Individual tests should override only the attributes they care about.
  3. Realistic but synthetic -- Test data should look realistic (proper email formats, valid phone numbers, plausible names) but never contain actual personal information. Use Faker libraries consistently.
  4. Deterministic when debugging -- Support seeded randomness so that a failing test can be reproduced with identical data. Log the seed in test output.
  5. Relationships are explicit -- When creating an order, the factory should explicitly create (or accept) the associated user and products. Implicit relationships lead to orphaned data and hidden dependencies.
  6. Clean up is non-negotiable -- Every factory-created record in a database must be cleaned up after the test. Leaked data causes flaky tests and obscures real failures.
  7. Type safety throughout -- Factories should leverage TypeScript's type system to ensure generated data matches application interfaces. A factory that produces invalid types defeats its own purpose.

Project Structure

tests/
factories/
base.factory.ts
user.factory.ts
product.factory.ts
order.factory.ts
review.factory.ts
address.factory.ts
index.ts
builders/
user.builder.ts
order.builder.ts
query.builder.ts
seeders/
database-seeder.ts
api-seeder.ts
test-environment.ts
traits/
user-traits.ts
order-traits.ts
fixtures/
static/
countries.json
currencies.json
snapshots/
seed-data.sql
helpers/
cleanup.ts
id-generator.ts
date-generator.ts
config/
factory.config.ts

Detailed Guide: The Base Factory Pattern

Core Factory Class

The base factory provides the foundation for all entity factories. It handles defaults, overrides, sequences, traits, and lifecycle hooks.

typescript
import { faker } from '@faker-js/faker';
type FactoryCallback<T> = (overrides?: Partial<T>) => T;
type AfterCreateHook<T> = (entity: T) => Promise<void>;
type TraitDefinition<T> = Partial<T> | (() => Partial<T>);
interface FactoryOptions {
seed?: number;
}
abstract class BaseFactory<T> {
protected faker = faker;
private afterCreateHooks: AfterCreateHook<T>[] = [];
private sequences: Map<string, number> = new Map();
private registeredTraits: Map<string, TraitDefinition<T>> = new Map();
constructor(options?: FactoryOptions) {
if (options?.seed !== undefined) {
this.faker.seed(options.seed);
}
}
/**
* Define the default shape of the entity.
* Subclasses must implement this method.
*/
abstract definition(overrides?: Partial<T>): T;
/**
* Build a single entity without persistence.
*/
build(overrides?: Partial<T>): T {
return { ...this.definition(), ...overrides } as T;
}
/**
* Build multiple entities without persistence.
*/
buildMany(count: number, overrides?: Partial<T>): T[] {
return Array.from({ length: count }, () => this.build(overrides));
}
/**
* Build an entity with named traits applied.
*/
buildWith(...traitNames: string[]): T {
let merged: Partial<T> = {};
for (const name of traitNames) {
const trait = this.registeredTraits.get(name);
if (!trait) {
throw new Error(`Unknown trait: "${name}". Register it with registerTrait().`);
}
const traitValue = typeof trait === 'function' ? trait() : trait;
merged = { ...merged, ...traitValue };
}
return this.build(merged);
}
/**
* Build and persist an entity using registered hooks.
*/
async create(overrides?: Partial<T>): Promise<T> {
const entity = this.build(overrides);
for (const hook of this.afterCreateHooks) {
await hook(entity);
}
return entity;
}
/**
* Build and persist multiple entities.
*/
async createMany(count: number, overrides?: Partial<T>): Promise<T[]> {
const entities: T[] = [];
for (let i = 0; i < count; i++) {
entities.push(await this.create(overrides));
}
return entities;
}
/**
* Register a lifecycle hook that runs after create().
*/
afterCreate(hook: AfterCreateHook<T>): this {
this.afterCreateHooks.push(hook);
return this;
}
/**
* Register a named trait for reuse across tests.
*/
registerTrait(name: string, definition: TraitDefinition<T>): this {
this.registeredTraits.set(name, definition);
return this;
}
/**
* Get the next value in a named sequence.
*/
protected sequence(name: string): number {
const current = this.sequences.get(name) || 0;
const next = current + 1;
this.sequences.set(name, next);
return next;
}
/**
* Reset all sequences. Call between test suites.
*/
resetSequences(): void {
this.sequences.clear();
}
}
User Factory Implementation
typescript
interface User {
id: string;
email: string;
name: string;
role: 'admin' | 'editor' | 'viewer';
status: 'active' | 'inactive' | 'suspended';
avatar?: string;
phone?: string;
address?: Address;
preferences: UserPreferences;
createdAt: Date;
updatedAt: Date;
}
interface UserPreferences {
theme: 'light' | 'dark';
language: string;
notifications: boolean;
timezone: string;
}
interface Address {
street: string;
city: string;
state: string;
zip: string;
country: string;
}
class UserFactory extends BaseFactory<User> {
constructor(options?: FactoryOptions) {
super(options);
this.registerDefaultTraits();
}
definition(): User {
const firstName = this.faker.person.firstName();
const lastName = this.faker.person.lastName();
const seq = this.sequence('user');
const now = new Date();
return {
id: this.faker.string.uuid(),
email: `test-user-${seq}@example.com`,
name: `${firstName} ${lastName}`,
role: 'viewer',
status: 'active',
avatar: this.faker.image.avatar(),
phone: this.faker.phone.number(),
preferences: {
theme: 'light',
language: 'en',
notifications: true,
timezone: 'America/New_York',
},
createdAt: now,
updatedAt: now,
};
}
private registerDefaultTraits(): void {
this.registerTrait('admin', { role: 'admin' });
this.registerTrait('editor', { role: 'editor' });
this.registerTrait('inactive', { status: 'inactive' });
this.registerTrait('suspended', { status: 'suspended' });
this.registerTrait('darkMode', {
preferences: {
theme: 'dark',
language: 'en',
notifications: true,
timezone: 'America/New_York',
},
});
this.registerTrait('withAddress', () => ({
address: {
street: this.faker.location.streetAddress(),
city: this.faker.location.city(),
state: this.faker.location.state(),
zip: this.faker.location.zipCode(),
country: 'US',
},
}));
}
}
// Usage examples
const userFactory = new UserFactory({ seed: 42 });
// Simple user with defaults
const user = userFactory.build();
// Admin user
const admin = userFactory.build({ role: 'admin' });
// User with traits
const darkModeAdmin = userFactory.buildWith('admin', 'darkMode');
// Multiple users
const users = userFactory.buildMany(10, { status: 'active' });
// User with specific overrides
const specificUser = userFactory.build({
email: 'specific@test.com',
name: 'Test User',
role: 'editor',
});

Detailed Guide: The Builder Pattern for Complex Objects

When objects have many optional fields or complex construction logic, the builder pattern provides a fluent API that is more readable than nested overrides.

typescript
class UserBuilder {
private data: Partial<User> = {};
private readonly factory = new UserFactory();
constructor() {
// Start with factory defaults
this.data = this.factory.build();
}
static create(): UserBuilder {
return new UserBuilder();
}
withId(id: string): this {
this.data.id = id;
return this;
}
withName(name: string): this {
this.data.name = name;
return this;
}
withEmail(email: string): this {
this.data.email = email;
return this;
}
withRole(role: User['role']): this {
this.data.role = role;
return this;
}
asAdmin(): this {
this.data.role = 'admin';
return this;
}
asEditor(): this {
this.data.role = 'editor';
return this;
}
withStatus(status: User['status']): this {
this.data.status = status;
return this;
}
active(): this {
this.data.status = 'active';
return this;
}
inactive(): this {
this.data.status = 'inactive';
return this;
}
suspended(): this {
this.data.status = 'suspended';
return this;
}
withAddress(overrides?: Partial<Address>): this {
this.data.address = {
street: overrides?.street ?? faker.location.streetAddress(),
city: overrides?.city ?? faker.location.city(),
state: overrides?.state ?? faker.location.state(),
zip: overrides?.zip ?? faker.location.zipCode(),
country: overrides?.country ?? 'US',
};
return this;
}
withPreferences(overrides: Partial<UserPreferences>): this {
this.data.preferences = {
...this.data.preferences!,
...overrides,
};
return this;
}
createdDaysAgo(days: number): this {
const date = new Date();
date.setDate(date.getDate() - days);
this.data.createdAt = date;
return this;
}
build(): User {
return this.data as User;
}
}
// Usage
const adminUser = UserBuilder.create()
.asAdmin()
.active()
.withName('Admin User')
.withEmail('admin@company.com')
.withAddress({ country: 'US', state: 'CA' })
.build();
Order Builder with Relationship Chaining
typescript
interface Order {
id: string;
userId: string;
items: OrderItem[];
subtotal: number;
tax: number;
shipping: number;
total: number;
status: 'pending' | 'confirmed' | 'shipped' | 'delivered' | 'cancelled';
shippingAddress: Address;
paymentMethod: string;
createdAt: Date;
updatedAt: Date;
}
interface OrderItem {
productId: string;
productName: string;
quantity: number;
unitPrice: number;
totalPrice: number;
}
interface Product {
id: string;
name: string;
slug: string;
description: string;
price: number;
currency: string;
category: string;
tags: string[];
sku: string;
inventory: number;
status: 'draft' | 'active' | 'archived';
createdAt: Date;
}
class OrderBuilder {
private order: Partial<Order> = {};
private _items: OrderItem[] = [];
private userFactory = new UserFactory();
static create(): OrderBuilder {
return new OrderBuilder();
}
constructor() {
this.order = {
id: faker.string.uuid(),
userId: faker.string.uuid(),
status: 'pending',
shippingAddress: {
street: faker.location.streetAddress(),
city: faker.location.city(),
state: faker.location.state(),
zip: faker.location.zipCode(),
country: 'US',
},
paymentMethod: 'credit_card',
createdAt: new Date(),
updatedAt: new Date(),
};
}
forUser(userId: string): this {
this.order.userId = userId;
return this;
}

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 90 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
76
Repository forks
1
7-day trend score
22

Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 17 Mar 2026, 8 months ago.

Extension points

  • hookPre/post lifecycle hooks
  • configConfiguration overrides

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/pramoddutta/qaskills/test-data-factory/badge)](https://verified-skill.com/skills/pramoddutta/qaskills/test-data-factory)

Something wrong with this skill or its page? Tell us.