Skip to content

Part Factory test entity factories

Part Factory is a minimalist object factory pattern for TypeScript. It helps you create strongly typed factories with useful default value generation, then override those defaults as needed in each test case.

Terminal window
npm install -D @kensio/part-factory

Suppose you have an object with this structure, and you want to generate valid instances for tests:

interface Foo { name: string; size: number; }

Part Factory lets you define reusable factories for those objects, with strongly typed defaults and strongly typed overrides.

Create a factory with suitable defaults, then override only the values that matter for the current test.

import { StaticFactory } from "@kensio/part-factory";
interface Foo {
name: string;
size: number;
}
const fooFactory = new StaticFactory({
name: "Foobar",
size: 10,
});
const defaultFoo = fooFactory.make();
// { name: "Foobar", size: 10 }
const myFoo = fooFactory.make({ size: 20 });
// { name: "Foobar", size: 20 }

Overrides are partial through the object structure, so you can override a nested value without replacing the whole tree.

const userProfile = userProfileFactory.make({
contact: { address: { city: "Manchester" } },
});