Giter Club home page Giter Club logo

factory's Introduction

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

factory's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

tbrien

factory's Issues

[Question] how would you see setting attributes that are related to each other?

Apologies if this is a dense question, but in this example I want the name and code to be related - e.g. the code should be the lowercase value of name - but name is generated using faker (or chancejs, etc).

export class ChannelFactory extends Factory<Channel> {

  entity = Channel;

  attrs = {
    name: () => `Web-${faker.datatype.number({ min: 1000, max: 9999 })}`,
    code: // should be the name .toLowerCase(),
    ...
  };
}

Do you have a suggested pattern in terms of how to handle this situation?

Thanks for the work so far on this tool, seems useful!

adapters, monorepo and deps

So far, typeorm is a dependency of this package and no other adapter is provided.
This won't be a good solution for long if we want new adapters and avoid useless dependencies.

We may decide to remove the typeorm part to a new repo or use a monorepo here and add adapters + dedicated factory's SubClass in different sections.

Right now, we need to try this library a bit before deciding to expand it to other use.

TypeScript support on `attrs` + show example of 1:N "SubFactory"

The readme mentions one to many relationships, but as far as I can tell the docs don't describe how this would be done.

In all situation's it seems that TS is unhappy with a Promise<MyType[]> - the promise being the issue.

It would be useful to have examples of One-to-Many, as well as Many-to-Many, and Many-to-One (the inverse).

LazyAttribute function

It would be nice to be able to have attrs depending on other attribute, example

attrs = {
  "name": new Sequence(n => `Adrien${n}`),
  "email": new LazyAttr(incompleteInstance => `${incompleteInstance}@example.com`)
}

Need:

  • tests
  • docs
  • implementation
  • profit

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.