Overwriting Property Values
To overwrite the property values of a factory, use .props
. In the example below, the value of firstName
is overwritten from John
to Alice
.
import { factory } from "@factory-js/factory";
const userFactory = factory.define({
props: {
firstName: () => "John",
lastName: () => "Doe",
},
vars: {},
});
const user = await userFactory.props({ firstName: () => "Alice" }).build();
console.log(user); // 👉 { "firstName": "Alice", "lastName": "Doe" }
.props
can be called multiple times in a method chain. If the same property value is overwritten multiple times, the last value takes precedence.
const user = await userFactory
.props({ firstName: () => "Alice", lastName: () => "Smith" })
.props({ firstName: () => "Bob" })
.props({ firstName: () => "Tom" })
.build();
console.log(user); // 👉 { firstName: "Tom", lastName: "Smith" }
You cannot add new properties with .props
. You can only overwrite the values
of properties defined in .define
. If you want to add properties, refer to
Extending Factory.
Defining Dependent Properties
You can also define properties that reference the values of other properties. In the example below, the value of fullName
is generated based on the values of firstName
and lastName
.
const userFactory = factory
.define({
props: {
firstName: () => "John",
lastName: () => "Doe",
// Dependent properties cannot be defined within `.define`, so set an empty string initially
fullName: () => "",
},
vars: {},
})
.props({
fullName: async ({ props }) =>
// Since there might be a Promise, you need to use `await` to get the property values
`${await props.firstName} ${await props.lastName}`,
});
// 👇 { fullName: "John Doe", firstName: "John", lastName: "Doe" }
console.log(await userFactory.build());
Avoid creating properties that reference each other circularly, as this could result in an infinite loop.
Note that dependent properties cannot be defined within .define
. Therefore, you need to set a dummy value such as an empty string initially and then overwrite the value later with .props
. This constraint helps keep the object within .define
simple, allowing TypeScript to correctly infer types.
FactoryJS provides a function called later
to easily define placeholder. For
more details, refer to Placeholder.
A convenient aspect of this feature is that it works correctly even if you change the value of a property later. For example, in the following example, the value of firstName
is changed from John
to Tom
after setting the value of fullName
, and the value of fullName
is updated automatically.
const userFactory = factory
.define({
props: {
firstName: () => "John",
lastName: () => "Doe",
fullName: "",
},
vars: {},
})
.props({
fullName: async ({ props }) =>
`${await props.firstName} ${await props.lastName}`,
});
const user = await userFactory.props({ firstName: () => "Tom" }).build();
// 👇 { fullName: "Tom Doe", firstName: "Tom", lastName: "Doe" }
console.log(await userFactory.build());