thoughtbot/fishery

Using one property's value in another

Closed this issue · 2 comments

Given the factory:

export default Factory.define<User>(() => ({
  firstName: 'John',
  lastName: 'Smith',
  fullName: `${firstName} ${lastName}`
}));

How can I use firstName and lastName to form the value for fullName dynamically?

I know I can use afterCreate/afterBuild but was wondering if there is a way to do it without them

What you want is params, which represents the values passed to build:

export default Factory.define<User>(({ params }) => {
  const {
    firstName = 'John', // use firstName from params or default value of 'John'
    lastName = 'Smith',
  } = params;
  const fullName = `${firstName} ${lastName}`;

  return {
    firstName,
    lastName,
    fullName,
  }
})

There's a similar example in the readme.