@adrien-may/factory

中文文档
2.1.0发布于 2026/01/13ISCTypeScriptCommonJS零依赖近 30 天下载 4189

🏭 Testing made easier with factories for your entities/models.

原始使用文档
文档目录9 节
  1. Installation
  2. Usage
  3. Factories
  4. SubFactories
  5. Sequences
  6. Lazy Attributes
  7. Lazy Sequences
  8. Post Generations
  9. Seeding (NEW)

Factory 🏭

This package makes testing easier by providing ways to create factories for your entities/models. Inspiration came from the Factory Boy 👦 python package and Factory Girl 👧.

npm version

Build

codecov

License: ISC Open Source Love

You can also have a look at these projects:

Installation

NPM

npm install @adrien-may/factory --save-dev

Yarn

yarn add @adrien-may/factory --dev

Usage

This section provides a quick overview of what you can achieve with this package.

Factories

Declaration

To declare a factory, you have to provide:

  • An adapter: ObjectAdapter, TypeormAdapter, ...
  • An entity [Optional without typeorm]: the model you are building
  • The fields to be populated (theirs default values or ways to generate them)

The adapter allows you to persist your data. If you want to save your data in a database via typeorm, you can use the TypeormAdapter . Default Adapter is ObjectAdapter and does not persist anything. You can create your own adapter to persist your data the way you want.

import { Factory } from '@adrien-may/factory';

// Object/Entity to create
class User {
  email: string;
  role: string;
}

// Factories
class UserFactory extends Factory<User> {
  entity = User;
  attrs = {
    email: '[email protected]',
    role: 'basic',
  };
  // By default, adapter is ObjectAdapter
}

class AdminUserFactory extends Factory<User> {
  entity = User;
  attrs = {
    email: '[email protected]',
    role: 'admin',
  };
}

// Usage
const adminFactory = new AdminUserFactory();
const admin1 = adminFactory.create();
const admins = adminFactory.createMany(5);
Typeorm
import { Factory, TypeormFactory, TypeormAdapter } from '@adrien-may/factory';
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

const dataSource = new DataSource({
  type: 'sqlite',
  database: ':memory:',
  ... // other typeorm options
});

@Entity()
class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column('text')
  email: string;
}

export class UserFactory extends TypeormFactory<User> {
  entity = User;
  attrs = {
    email: '[email protected]',
  };
}

// Usage
const userFactory = new UserFactory(dataSource);
const user = userFactory.create();
const users = userFactory.createMany(5);
Object and interfaces

You could use directly the factory without a defined entity and provide only an interface.

import { ObjectFactory } from '@adrien-may/factory';

interface User {
  name: string;
}

class UserFactory extends ObjectFactory<User> {
  // No entity defined
  attrs = {
    name: 'John Doe',
  };
}

// Usage
const userFactory = new UserFactory();
const user = userFactory.create();
const users = userFactory.createMany(5);
Custom

You may want to use factory with other ORMs or CMS. To illustrate it we will demonstrate how you would create a factory for payload cms

For this, you should first create an adapter.

import { Adapter } from '@teammay/factory'
import {
  DataFromCollectionSlug,
  RequiredDataFromCollectionSlug,
} from 'node_modules/payload/dist/collections/config/types'

interface PayloadArgs {
  draft: boolean;
  locale: string
}

class PayloadAdapter extends Adapter<S extends CollectionSlug, [PayloadArgs?]> {
    constructor(
    private payload: Payload,
    private slug: S,
  ) {}

  async save(
    instance: RequiredDataFromCollectionSlug<S> | RequiredDataFromCollectionSlug<S>[],
    { draft = false, locale = 'en' }: PayloadArgs = { draft: false, locale: 'en' },
  ): Promise<DataFromCollectionSlug<S> | DataFromCollectionSlug<S>[]> {
    const instances = Array.isArray(instance) ? instance : [instance]
    const savedInstances = await Promise.all(
      instances.map((data) =>
        this.payload.create({
          collection: this.slug,
          data,
          draft,
          locale,
        }),
      ),
    )
    return Array.isArray(instance) ? savedInstances : savedInstances[0]
  }

}

Now with this adapter, we can create a PayloadFactory class

import { Factory } from '@teammay/factory'
import {
  DataFromCollectionSlug,
  RequiredDataFromCollectionSlug,
} from 'node_modules/payload/dist/collections/config/types'
import { CollectionSlug, Payload } from 'payload'



abstract class PayloadFactory<S extends CollectionSlug> extends Factory<DataFromCollectionSlug<S>, [PayloadArgs?]> {
  constructor(protected payload: Payload, protected slug: S) {
    super()
    this.adapter = new PayloadAdapter(payload, slug)
  }
}

With this class we can now instantiate factories for every payload collections. For instance if we have a collection with slug 'author' and containing only one field 'name' we would do :


interface User {
  name: string;
}

class UserFactory extends PayloadFactory<'author'> {
  // No entity defined
  attrs = {
    name: 'John Doe',
  };
}

// Usage
const userFactory = new UserFactory();
const user = userFactory.create({}, {draft: true, locale: 'fr'});
const users = userFactory.createMany(5, {}, {draft: false, locale: 'es'});

Fuzzy generation with Fakerjs/Chancejs/

To generate pseudo random data for our factories, we can take advantage of libraries like:

import { TypeormFactory } from '@adrien-may/factory';
import Chance from 'chance';

const chance = new Chance();

export class ProfileFactory extends TypeormFactory<Profile> {
  entity = Profile;
  attrs = {
    name: () => chance.name(),
    email: () => chance.email(),
    description: () => chance.paragraph({ sentences: 5 }),
  };
}

Note: Faker/Change are not included in this library. We only use the fact that a function passed to attrs is called every time a factory is created. Thus, you can use Faker/Chancejs to generate data.

Exploiting our created factories

We can use our factories to create new instances of entities:

const userFactory = new UserFactory();

For typeorm factories you should either set a default factory using:

import { setDefaultFactory } from '@adrien-may/factory';
{...}
setDefaultDataSource(typeormDatasource)
{...}
const userFactory = new UserFactory();

Or set a datasource for each instances using:

const userFactory = new UserFactory(typeormDatasource);

The factory and its adapters expose some functions:

  • build: to create an object (and eventually generate data / subFactories)
  • create: same as make but persist object in database via ORM "save" method
  • buildMany and createMany allow to create several instances in one go
const user: User = await userFactory.create();
const users: User[] = await userFactory.createMany(5);

To override factory default attributes, add them as parameter to the create function:

const user: User = await userFactory.create({ email: '[email protected]' });

SubFactories

It is fairly common for entities to have relations (manyToOne, oneToMany, oneToOne etc...) between them. In this case we create factories for all the entities and make use of SubFactory to create a link between them. SubFactories will be resolved when instances are built. Note that this is pure syntactic sugar as one could use an arrow function calling another factory.

Example

If one user has a profile entity linked to it: we use the UserFactory as a SubFactory on the ProfileFactory

import { Factory, SubFactory } from '@adrien-may/factory';
import { UseFactory } from './user.factory.ts'; // factory naming is free of convention here, don't worry about it.

export class ProfileFactory extends Factory<Profile> {
  entity = Profile;
  attrs = {
    name: 'Handsome name',
    user: new SubFactory(UserFactory, { name: 'Override factory name' }),
  };
}

Sequences

Sequences allow you to get an incremental value each time it is ran with the same factory. That way, you can use a counter to have more meaningful data.

import { Factory, Sequence } from '@adrien-may/factory';

export class UserFactory extends Factory<User> {
  entity = User;
  attrs = {
    customerId: new Sequence((nb: number) => `cust__abc__xyz__00${nb}`),
  };
}

Lazy Attributes

Lazy attributes are useful when you want to generate a value based on the instance being created. They are resolved after every other attribute but BEFORE saving the entity. For any action "post save", use the PostGenerate hook.

import { Factory, LazyAttribute } from '@adrien-may/factory';

export class UserFactory extends Factory<User> {
  entity = User;
  attrs = {
    name: 'Sarah Connor',
    mail: new LazyAttribute(instance => `${instance.name.toLowerCase()}@skynet.org`),
  };
}

Lazy Sequences

Lazy sequences combine the power of sequences and lazy attributes. The callback is called with an incremental number and the instance being created.

import { Factory, LazySequence } from '@adrien-may/factory';

export class UserFactory extends Factory<User> {
  entity = User;
  attrs = {
    name: 'Sarah Connor',
    mail: new LazySequence((nb, instance) => `${instance.name.toLowerCase()}.${nb}@skynet.org`),
  };
}

Post Generations

To perform actions after an instance has been created, you can use the PostGeneration decorator.

import { Factory, PostGeneration } from '@adrien-may/factory';

export class UserFactory extends Factory<User> {
  ...

  @PostGeneration()
  postGenerationFunction() {
    // perform an action after creation
  }

  @PostGeneration()
  async actionOnCreatedUser(user: User) {
    // do something with user
  }
}

Adapters

You can provide your own adapter to extend this library. This library provides for now ObjectAdapter (default) and TypeormAdapter . To ease testing, this library provides a TypeormFactory class.

The following example shows how to use them:

import { Factory, TypeormFactory, TypeormAdapter } from '@adrien-may/factory';

export class UserFactory extends Factory<User> {
  entity = User;
  attrs = {
    email: '[email protected]',
    role: 'basic',
  };
  adapter = TypeormAdapter();
}

// Same as:
export class TypeormUserFactory extends TypeormFactory<User> {
  entity = User;
  attrs = {
    email: '[email protected]',
    role: 'admin',
  };
}

Seeding (NEW)

You can now easily seed your database using your factories with the runSeed utility.

Example

Create a seed.ts file in your project:

import { runSeed } from '@adrien-may/factory';
import { UserFactory } from './factories/user.factory';
import { PostFactory } from './factories/post.factory';
import { dataSource } from './db'; // your TypeORM DataSource

export let fixtures: any = {};

async function main() {
  fixtures = await runSeed({
    dataSource,
    factories: { UserFactory, PostFactory },
    seeds: async ({ UserFactory, PostFactory }) => {
      const users = await UserFactory.createMany(10);
      const posts = await PostFactory.createMany(20);
      return {
        users,
        posts,
      };
    },
  });
}

main();
  • All factories are instantiated with the provided dataSource.
  • You can use all factory methods (create, createMany, etc) inside the seeds function.
  • This utility is framework-agnostic but works best with TypeORM.
  • You can access created instances via the fixtures object.

Example: Seeding in Jest setup

You can also use runSeed in your Jest setup to ensure your test database is seeded before tests run:

// jest.setup.ts
import { runSeed } from '@adrien-may/factory';
import { UserFactory } from './factories/user.factory';
import { dataSource } from './db';

beforeAll(async () => {
  await runSeed({
    dataSource,
    factories: { UserFactory },
    seeds: async ({ UserFactory }) => {
      await UserFactory.createMany(5);
    },
  });
});

Example: Running seeds via npm

Add this to your package.json scripts:

"scripts": {
  "seed": "ts-node ./seed.ts"
}

Then run:

npm run seed

版本与发布记录

@adrien-may/factory 共发布 15 个版本,首次发布于 2022/01/13;过去 12 个月发布了 3 个版本。

版本发布日期距今
2.1.0latest2026/01/139 个月前
2.0.42025/11/2711 个月前
2.0.32025/11/2711 个月前
2.0.22025/11/061 年前
2.0.12025/11/031 年前
2.0.02025/11/031 年前

关于 @adrien-may/factory 的常见问题

@adrien-may/factory 是什么?

🏭 Testing made easier with factories for your entities/models.

如何安装 @adrien-may/factory?

在项目目录运行 npm install @adrien-may/factory,或使用 pnpm add / yarn add / bun add。

@adrien-may/factory 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@adrien-may/factory 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@adrien-may/factory 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@adrien-may/factory 可以商用吗?

@adrien-may/factory 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@adrien-may/factory 的下载量有多少?

根据 npm 官方下载统计,@adrien-may/factory 在 2026/10/05 – 2026/11/03 这 30 天内被下载 4,189 次,日均约 140 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@adrien-may/factory 还在维护吗?

最新版本 2.1.0 发布于 2026/01/13(9 个月前);至今共发布 15 个版本,其中过去 12 个月发布了 3 个;首次发布于 2022/01/13。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。