The object generator for testing.
Get Startedimport { 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));
[
{
"firstName": "John",
"lastName": "Doe",
"fullName": "John Doe"
},
{
"firstName": "John",
"lastName": "Doe",
"fullName": "John Doe"
}
]
TypeScript warns you about mis-configuration and typos.
Written in simple JavaScript, it can be used on any framework.
It is very lightweight as it does not depend on any other packages.
You can define variables, traits, and properties that depend on other properties.
Designed to be used also with ORMs like Prisma and Drizzle.
Using the FactoryJS plugin for Prisma, you can automatically generate factories from schemas.
An example of combining libraries:
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 Startedimport { 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);
});
});