0.8.2 • Published 3 years ago

object-factory-bot v0.8.2

Weekly downloads
495
License
MIT
Repository
github
Last release
3 years ago

A simple object factory

Build Status

Uses Proxy objects to create a DSL for object construction. Requires Proxy support, which is supported by modern browsers and Node 6 and above. https://caniuse.com/#search=Proxy http://node.green/#ES2015-built-ins-Proxy

import { sample } from 'lodash';
import faker from 'faker'; // https://github.com/marak/Faker.js
Factory.defaults = { // counld also be a function
  driver: 'Speedy',
};
Factory.define('manufacturer')
    .name(() => sample(['Ford', 'GM', 'Mercedes']))

Factory.define('wheel')
    .diameter(Math.round(Math.random() * 6)+ 15)
    .brand(({ siblings }) => siblings && siblings.length ? siblings[0].brand : sample(['Firestone', 'Cooper', 'Bridgestone']));

Factory.define('car')
    .id(Factory.sequence) // driver is set in defaults
    .owner(({ diver }) => driver || faker.name.findName())
    .manufacturer(Factory.reference('manufacturer'))
    .wheels(Factory.reference('wheel', { count: 4 }));

const car = Factory.create('car', { owner: 'Jillian West', manufacturer: { name: 'Tesla' } });

car will be a plain object looking something like:

    { id: 1,
      owner: 'Jillian West',
      manufacturer: { name: 'Tesla' },
      wheels:
       [ { diameter: 20, brand: 'Bridgestone' },
         { diameter: 20, brand: 'Bridgestone' },
         { diameter: 20, brand: 'Bridgestone' },
         { diameter: 20, brand: 'Bridgestone' } ] }

References support options:

  • count: can be either a function or number. If not provided, the reference will be a single object. If provided, the reference will be an array with count elements.
  • defaults: Also can be either a function or number. The default values will override whatever is specified by the referenced child's property values, but will not override the context that is passed into the factory itself.

See also:

Both of the above seem to be fairly complex and oriented towards createing classes.

For my purposes I just wanted a way to create plain objects.

I also wanted the property name to appear first in the object specification so that it's easier to read.

0.8.1

3 years ago

0.8.2

3 years ago

0.8.0

3 years ago

0.7.4

3 years ago

0.7.2

3 years ago

0.7.1

3 years ago

0.7.3

3 years ago

0.7.0

3 years ago

0.6.1

5 years ago

0.6.0

5 years ago

0.5.4

6 years ago

0.5.3

6 years ago

0.5.2

6 years ago

0.5.1

6 years ago

0.5.0

6 years ago

0.4.3

6 years ago

0.4.1

6 years ago

0.4.0

6 years ago

0.3.0

6 years ago

0.2.2

6 years ago

0.2.1

6 years ago

0.2.0

6 years ago

0.1.0

6 years ago