Core Concepts

Overriding and excluding

Customize generated data with set() and without()

In v2, partial selection is achieved via the fluent builder using .set() to override values and .without() to exclude fields. This works for simple fields, relations, arrays, and nested paths.

Basic overrides

class User {
  @FactoryValue(faker => faker.number.int())
  id: number;
 
  @FactoryValue(faker => faker.person.firstName())
  firstName: string;
 
  @FactoryValue(faker => faker.person.lastName())
  lastName: string;
 
  @FactoryValue(faker => faker.internet.email())
  email: string;
}
 
const user = factory
  .one(User)
  .set('firstName', 'Jane')
  .set('email', 'jane@example.com')
  .make();

Excluding fields

const anonymous = factory
  .one(User)
  .without('email')
  .without('lastName')
  .make();

Nested overrides with relations

class Avatar {
  @FactoryValue(faker => faker.image.url())
  url: string;
 
  @FactoryValue(faker => faker.number.int())
  width: number;
}
 
class Profile {
  @FactoryValue(faker => faker.lorem.sentence())
  bio: string;
 
  @FactoryType(() => Avatar)
  avatar: Avatar;
}
 
const profile = factory
  .one(Profile)
  .with('avatar')
  .set('avatar.url', 'https://cdn.example.com/avatar.png')
  .without('avatar.width')
  .make();

Arrays: sizes and overrides

class Comment {
  @FactoryValue(faker => faker.number.int())
  id: number;
 
  @FactoryValue(faker => faker.lorem.sentence())
  text: string;
}
 
class Post {
  @FactoryValue(faker => faker.number.int())
  id: number;
 
  @FactoryType(() => [Comment])
  comments: Comment[];
}
 
const post = factory
  .one(Post)
  .with(2, 'comments')
  .set('comments.0.text', 'Pinned comment')
  .without('comments.1.text')
  .make();

Rules:

  • Call .with() before .set()/.without() when targeting nested paths.
  • Supplying negative amounts to .with() throws.

On this page