ts-mock-autofixture-kit
v0.1.7
Published
A professional TypeScript fixture generator for mocking interfaces and classes, inspired by AutoFixture.
Downloads
16
Maintainers
Readme
ts-mock-autofixture-kit
A lightweight, flexible, and deterministic TypeScript mock data generator. Automatically produces rich fixtures for interfaces/classes with smart sequencing, overrides, seeding, and nested hydration — ideal for unit tests, snapshots, component testing, and prototyping.
✨ Key Features
- ⚡ Instant mocks from interfaces or classes (
create,fixtureOf) - 🔁 List generation with smart sequencing (
createList) - 🧩 Per-field customization via
.with(...) - 🎯 Bulk overrides with
withDefaults - 🔢 Deterministic sequencing by property name patterns (e.g.,
*_id,name,code,character) — transparently generatescredit-1,character-1, etc. - 🧪 Reproducible mocks via
seed - 🧠 Intelligent defaults: strings, numbers, booleans, dates, arrays, nested objects
- 🔧 Known-keys hydration to limit eager generation
- 🧰
withSequencehelper for explicit incremental values - 🌱 100% TypeScript, no decorators or runtime magic
- ✅ Compatible with Jest / Vitest / Mocha / Jasmine / React testing
📦 Installation
npm install --save-dev ts-mock-autofixture-kit
# or
yarn add --dev ts-mock-autofixture-kit🚀 Quick Start
Basic interface mock
import { create } from 'ts-mock-autofixture-kit';
interface User {
id: string;
name: string;
isActive: boolean;
}
const user = create<User>(); // { id: '...', name: '...', isActive: true/false }Mocking a class
class Product {
id!: number;
title!: string;
}
const product = create<Product>(Product); // instance of Product with filled propsList of mocks with sequencing & seed
import { createList } from 'ts-mock-autofixture-kit';
interface Cast {
credit_id: string;
character: string;
}
const credits = createList<Cast>(3, { seed: 100 });
// credit_id: ["credit-1","credit-2","credit-3"]
// character: ["character-1","character-2","character-3"]🔧 Advanced Usage
Full control: fixtureOf
import { fixtureOf } from 'ts-mock-autofixture-kit';
const user = fixtureOf<User>()
.with('name', () => 'Alice')
.with('isActive', () => true)
.create();Deterministic mocks using seed
const u1 = fixtureOf<User>({ seed: 42 }).create();
const u2 = fixtureOf<User>({ seed: 42 }).create();
expect(u1).toEqual(u2); // same content
const list1 = createList<User>(3, { seed: 123 });
const list2 = createList<User>(3, { seed: 123 });
expect(JSON.stringify(list2)).toBe(JSON.stringify(list1));Custom global generators
const customGenerators = {
string: () => 'fixed',
number: () => 7,
boolean: () => false,
date: () => new Date('2000-01-01'),
array: () => ['x', 'y'],
object: () => ({ foo: 'bar' }),
function: () => () => 'fn',
};
const user = fixtureOf<User>(customGenerators)
.with('roles', () => ['admin', 'editor'])
.create();Limit hydration with known keys
const partial = fixtureOf<User>(undefined, ['name', 'age']).create();
// only `name` and `age` are eagerly generated; others are lazyBulk override: withDefaults
const user = fixtureOf<User>()
.withDefaults({ name: 'Bob', active: false })
.create();Explicit sequencing: withSequence
interface SequenceItem {
code: string;
}
const f = fixtureOf<SequenceItem>();
const first = f.withSequence('code', 'item-').create(); // item-1
const second = f.withSequence('code', 'item-').create(); // item-2🧠 Smart Auto-Generation Heuristics
The library inspects property names and applies intuitive defaults:
| Pattern / Name | Behavior / Generator |
|--------------------------------------|----------------------------------|
| id, name | string() |
| *_id, credit_id | Sequenced string like credit-1 |
| age, count, vote, popularity | number() |
| is*, has*, active | boolean() |
| *date | Date object |
| Plural-ish (roles, items, list)| Arrays (with nested object support) |
| Nested objects | Recursively proxied and hydrated |
Sequencable keys are automatically detected by default: things ending in _id or containing name, code, character, etc., and will receive incrementing suffixes when generating lists (createList).
🧪 Testing Examples
Unit / Snapshot (Jest)
import { create, fixtureOf, createList } from 'ts-mock-autofixture-kit';
interface User {
id: string;
name: string;
active: boolean;
}
test('snapshot user with seed', () => {
const user = create<User>({ seed: 2025 });
expect(user).toMatchSnapshot();
});
test('override and verify', () => {
const user = fixtureOf<User>()
.with('name', () => 'TestName')
.withDefaults({ active: true })
.create();
expect(user.name).toBe('TestName');
expect(user.active).toBe(true);
});React component test (simplified)
import { render, screen } from '@testing-library/react';
import { fixtureOf, createList } from 'ts-mock-autofixture-kit';
import { ActorPage } from './ActorPage';
import { Actor } from '../models/actor.model';
import { ActorCast } from '../models/actorCast.model';
process.env.REACT_APP_IMAGES_URL ||= 'https://example.com/';
// Transparent generation; no manual sequencing needed
const mockActor = fixtureOf<Actor>({ seed: 42 }).create();
const mockCredits = createList<ActorCast>(3, { seed: 100 });
jest.mock('../hooks/useActor', () => ({
useActor: () => ({ actor: mockActor, credits: mockCredits }),
}));
jest.mock('../components/CreditsCard', () => ({
__esModule: true,
CreditsCard: ({ credit }: any) => <div data-testid="card">{credit.character}</div>,
}));
jest.mock('react-router-dom', () => ({
useParams: () => ({ id: 'foo' }),
}), { virtual: true });
test('renders actor page with credits', () => {
render(<ActorPage />);
const cards = screen.getAllByTestId('card');
expect(cards).toHaveLength(3);
expect(cards[0].textContent).toMatch(/character-/);
});🧩 Example with Arbitrary Types
interface Comment {
comment_id: string;
author_name: string;
content: string;
}
const comments = createList<Comment>(2, { seed: 10 });
// comment_id: ["comment-1", "comment-2"]
// author_name: ["author_name-1", "author_name-2"]
// content: stringinterface Session {
session_code: string;
user_id: string;
metadata: Record<string, any>;
}
const sessions = createList<Session>(2, { seed: 5 });
// session_code: ["session_code-1","session_code-2"]
// user_id: ["user-1","user-2"]🛠 API Reference
| Export / Method | Description |
|--------------------------------|-------------|
| create<T>(...) | Generate a single mock (supports class constructor overload). |
| createList<T>(count, opts?) | Generate a list of mocks; accepts { seed } or full generator/options. |
| fixtureOf<T>(...) | Acquire a configurable Fixture<T> for with, withDefaults, withSequence, etc. |
| .with(key, genFn) | Override a single field generator. |
| .withDefaults(obj) | Bulk override multiple fields. |
| .withSequence(key, prefix) | Create incremental values for a key. |
| .create() | Materialize a mock from current fixture configuration. |
| .buildList(count) | Materialize a list from the fixture. |
| createSequencedList<T>(...) | Helper to build lists with a sequenced property (e.g., id-1, id-2, ...). |
🧪 Best Practices
- Use
seedto stabilize snapshots and make tests reproducible. - Combine
withDefaults+knownKeysto limit and speed up expensive fixtures. - Prefer auto sequencing in
createListover manual post-processing for common patterns. - Access properties before serializing if relying on lazy hydration or use
toRawto flatten proxies.
📁 Suggested Test Presets
import { fixtureOf } from 'ts-mock-autofixture-kit';
import { Actor } from '../../models/actor.model';
import { ActorCast } from '../../models/actorCast.model';
export const defaultActor = (seed?: number) =>
fixtureOf<Actor>({ seed }).create();
export const defaultCredit = (index: number, baseSeed = 100) =>
fixtureOf<ActorCast>({ seed: baseSeed + index }).create();Usage:
import { defaultActor, defaultCredit } from '../test/utils/presets';
const actor = defaultActor(42);
const credits = [0,1,2].map(i => defaultCredit(i));📁 Project Structure
📦 ts-mock-autofixture-kit
┣ 📂 src
┃ ┣ 📄 factory.ts
┃ ┣ 📄 Fixture.ts
┃ ┣ 📄 serializer.ts
┃ ┣ 📄 types.ts
┃ ┣ 📄 utils.ts
┣ 📂 tests
┃ ┣ 📄 index.test.ts
┣ 📄 README.md
┣ 📄 package.json
┣ 📄 tsconfig.json
┗ 📄 jest.config.js🛠 Built With
- TypeScript
- Jest / Vitest / Mocha / Jasmine
📄 License
MIT License © 2025 Ana Chávez
🔗 Links
- NPM: https://www.npmjs.com/package/ts-mock-autofixture-kit
- GitHub: https://github.com/anitachan/ts-mock-autofixture-kit
