npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@adrien-may/factory

v0.3.0

Published

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

Downloads

2,686

Readme

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

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: 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';

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

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

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',
  };
}

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
  }
}

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]' });