willryan / factory.ts

A library to ease creation of factories for test data for Typescript
MIT License
425 stars 23 forks source link

Feature request: traits! #6

Open jessepinho opened 6 years ago

jessepinho commented 6 years ago

This idea is inspired by factory_bot. Off the top of my head, it could look something like this:

interface Person {
  id: number
  firstName: string
  lastName: string
  fullName: string
  age?: number
}

const personFactory = Factory.makeFactory<Person>({
  id: Factory.each(i => i),
  firstName: 'Bob',
  lastName: 'Smith',
  fullName: 'Robert J. Smith, Jr.',
}, {
  traits: {
    withAge: {
      age: Factory.each(i => 20 + (i % 10)),
    }
  }
})

Then it could be consumed e.g.: const person = personFactory().traits().withAge() or const person = personFactory().traits("withAge") or similar.

Thoughts?

willryan commented 6 years ago

I created the ability to combine factories in #9. I think should handle your case, but let me know if there is a use case it won't cover.

ertrzyiks commented 2 years ago

What I liked about traits is the ability to create specialized factories, shortcuts for predefined states.

interface User {
  id: number,
  status: 'applied' | 'active',
  activatedAt: string | null
}

const userFactory = Factory.makeFactory<User>({
  id: 1,
  status: 'active',
  activatedAt: '2022-03-09T19:44:14.496Z'
}, {
  traits: {
    applied: {
      status: 'applied',
      activatedAt: null  
    }
  }
})
userFactory.build() // { id: 1, status: 'active', activatedAt: '2022-03-09T19:44:14.496Z' }
userFactory.trait('applied').build() // { id: 1, status: 'applied', activatedAt: null }

It's possible with combining factories, but the API is not convenient.