FactoryJS

The object generator for testing.

Get Started
factory.ts
import { factory } from "@factory-js/factory";

const userFactory = factory
  .define({
    props: {
      firstName: () => "John",
      lastName: () => "Doe",
      fullName: later<string>(),
    },
    vars: {},
  })
  .props({
    fullName: async ({ props }) =>
      `${await props.firstName} ${await props.lastName}`
  });

console.log(await userFactory.buildList(2));
Output
[
  {
    "firstName": "John",
    "lastName": "Doe",
    "fullName": "John Doe"
  },
  {
    "firstName": "John",
    "lastName": "Doe",
    "fullName": "John Doe"
  }
]

Features

  • Type Safety

    TypeScript warns you about mis-configuration and typos.

  • Framework Agnostic

    Written in simple JavaScript, it can be used on any framework.

  • Lightweight

    It is very lightweight as it does not depend on any other packages.

  • Highly Functional

    You can define variables, traits, and properties that depend on other properties.

  • ORM-Friendly API

    Designed to be used also with ORMs like Prisma and Drizzle.

  • Plugins

    Using the FactoryJS plugin for Prisma, you can automatically generate factories from schemas.

For example, you can use FactoryJS for...

Testing

An example of combining libraries:

FactoryJS

Using FactoryJS, you can save the objects needed for testing to the database with just a small amount of code. It is also easy to generate objects in different states, such as admin users and guest users, depending on the test case.

Get Started
import { userFactory } from "./user-factory.ts";

// Function to be tested
const isAdmin = (user: User) => {
  return user.role === "admin"
}

describe("when a user is admin", () => {
  it("returns true", async () => {
    const user = await userFactory(db) 
      .props({ role: () => "admin" }) 
      .build(); 

    expect(isAdmin(user)).toBe(true);
  });
});

describe("when a user is guest", () => {
  it("returns false", async () => {
    const user = await userFactory(db) 
      .props({ role: () => "guest" }) 
      .build(); 

    expect(isAdmin(user)).toBe(false);
  });
});