Test Data Factory
БесплатноБез исполняемых скриптовНе проверенBuild reusable test data factories with realistic fake data generation, relationship handling, and deterministic seeding for reproducible tests.
от PramodDutta★ 253 звезды на GitHubОб этом скилле
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
- Factories over fixtures -- Static fixture files become stale and brittle. Factories generate fresh, valid data on demand, adapting to schema changes automatically.
- 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.
- 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.
- Deterministic when debugging -- Support seeded randomness so that a failing test can be reproduced with identical data. Log the seed in test output.
- 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.
- 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.
- 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.
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 {
Установить Test Data Factory в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Test Data Factory?
Build reusable test data factories with realistic fake data generation, relationship handling, and deterministic seeding for reproducible tests.
Как установить скилл Test Data Factory?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Test Data Factory запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic