myfactoria
v1.0.1
Published
Simplistic model factory for JavaScript
Downloads
3
Maintainers
Readme
Simplistic model factory for JavaScript, heavily inspired by Laravel's Model Factories.
Install
$ yarn add myfactoria --dev
Note: If Node complains about
regeneratorRuntime
not defined, install and require babel-polyfill into your setup.
Usage
1. Define a model
To define a model, import and use define
from the module. define
accepts two arguments:
name
: (string) Name of the model, e.g.'user'
(faker)
(function) A closure to return the model's attribute definition as an object. This closure will receive an instance of the Faker JavaScript library, which allows you to generate various random testing data.
Example:
const define = require('myfactoria').define
define('User', faker => ({
id: faker.random.number(),
name: faker.name.findName(),
email: faker.internet.email(),
age: faker.random.number({ min: 13, max: 99 })
}))
2. Create model objects
To create model objects, import the factory and call it on the model's defined name. Following the previous example:
import factory from 'myfactoria'
// The simplest case, returns a "user" object
const user = factory('User')
// Generate a "user" object with "email" preset to "[email protected]"
const userWithSetEmail = factory('User', { email: '[email protected]' })
// Generate an array of 5 "user" objects
const users = factory('User', 5)
// Generate an array of 5 "user" objects, each with "age" preset to 27
const usersWithSetAge = factory('User', 5, { age: 27 })
// Use a function as an overriding value. The function will receive a faker instance.
const user = factory('User', {
name: faker => {
return faker.name.findName() + ' Jr.'
}
})
Test setup tips
Often, you want to set up all model definitions before running the tests. One way to do so is to have one entry point for the factories during test setup. For example, you can have this test
script defined in package.json
:
"test": "mocha-webpack --require test/setup.js tests/**/*.spec.js"
Or, if Jest is your thing:
"jest": {
"setupTestFrameworkScriptFile": "<rootDir>/test/setup.js"
}
Then in test/setup.js
you can require('myfactoria')
and add the model definitions there. myfactoria itself uses this approach for its tests.
Another approach is to have a wrapper module around myfactoria, have all models defined inside the module, and finally export
myfactoria itself. You can then import
the wrapper and use the imported object as a myfactoria instance (because it is a myfactoria instance), with all model definitions registered:
// tests/factory.js
import factory from 'myfactoria'
// define the models
factory.define('User', faker => ({}))
.define('Group', faker => ({}))
// now export myfactoria itself
export default factory
// tests/user.spec.js
import factory from './factory'
// `factory` is a myfactoria function instance
const user = factory('User')
License
MIT © Katkam Ravikanth