Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

Test Data Factory

БесплатноБез исполняемых скриптовНе проверен

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

PramodDuttaот 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

  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.

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 {
Полный SKILL.md на GitHub

Установить 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), без исполняемых скриптов.

Похожие скиллы

Сравнить Test Data Factory с