Factory
Create and distribute test fixtures/factories.
Usage
All examples assume you have required object-factory like this:
var Factory = require('object-factory');
Basic task syntax
function Event(props) {
this.title = props.title;
this.location = props.location;
}
var EventFactory = new Factory({
object: Event
properties: {
title: 'Amazing Event',
location: 'Bahamas'
}
});
var event = EventFactory.build({
title: 'xxx'
});
var event = EventFactory.create({
title: 'xxx'
});
Options for factories
When creating factories there are various options that can be passed.
.properties
new Factory({
properties: {
key: 'default value
'
}
});
The .properties
property (sorry) specify the default values for a
given factory.
.object
var MyThing = new Factory({
object: ThingWithConstructorThatAcceptsObjects
});
As the fictional object might suggest object is the object that the
factories properties are passed into...
MyThing.create({ xfoo: true });
new ThingWithConstructorThatAcceptsObjects({ xfoo: true })
.onbuild
The onbuild
property will be called if given before the generated
properties are passed to the constructor .object
.
var BuildMe = new Factory({
onbuild: function(builtObject) {
}
})
.oncreate
The oncreate
property will be called if given after the generated
properties are passed to the constructor .object
.
var BuildMe = new Factory({
object: Xfoo
oncreate: function(object) {
}
})
Composing factories
You can't create abritrarty depth in a factory. Each factory must be
one object deep but multiple factories can be referenced as properties
to create this nesting.
var Person = new Factory({
properties: {
name: 'James Lal'
}
});
var Event = new Factory({
properties: {
title: 'Amazing Event',
location: 'Bahamas',
person: Person
}
});
Inheritance
Factories can inherit from other factories:
var Developer = Person.extend({
properties: {
OCD: true
}
});
Testing Factories
object factory ships with a object-factory-viewer
binary which will
pretty print the output of your factory given a module.
module.exports = new Factory({
properties: { xfoo: 'foo' }
});
./node_modules/.bin/object-factory-viewer xfoo.js
If your not using .onbuild or .oncreate then this is a great way to test
the output of your factories. This serves as a good sanity check (and
could be used as documentation too).