All Projects → phanan → factoria

phanan / factoria

Licence: MIT license
Simplistic model factory for Node/JavaScript

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to factoria

virtio
Virtio implementation in SystemVerilog
Stars: ✭ 38 (-22.45%)
Mutual labels:  model
ModelSynchro
A JSON model generator for Swift 4
Stars: ✭ 19 (-61.22%)
Mutual labels:  model
GLM
Code for the General Lake Model
Stars: ✭ 30 (-38.78%)
Mutual labels:  model
interface-forge
Graceful mock-data and fixtures generation using TypeScript
Stars: ✭ 58 (+18.37%)
Mutual labels:  factory
pydantic-factories
Simple and powerful mock data generation using pydantic or dataclasses
Stars: ✭ 380 (+675.51%)
Mutual labels:  factory
trans-dsl
a transaction model framework, seems simple but powerful
Stars: ✭ 64 (+30.61%)
Mutual labels:  model
acorn-db
Provides Acorn projects with Eloquent Models for WordPress data.
Stars: ✭ 30 (-38.78%)
Mutual labels:  model
covid19 scenarios data
Data preprocessing scripts and preprocessed data storage for COVID-19 Scenarios project
Stars: ✭ 43 (-12.24%)
Mutual labels:  model
angular-github-api-factory
AngularJS Factory for GitHub v3 JSON REST API requests
Stars: ✭ 13 (-73.47%)
Mutual labels:  factory
gltf-bounding-box
Computes the global bounding box of a gltf model
Stars: ✭ 18 (-63.27%)
Mutual labels:  model
Odin
manage model revisions with ease
Stars: ✭ 60 (+22.45%)
Mutual labels:  model
darkgreybox
DarkGreyBox: An open-source data-driven python building thermal model inspired by Genetic Algorithms and Machine Learning
Stars: ✭ 25 (-48.98%)
Mutual labels:  model
angular-youtube-api-factory
AngularJS Factory for Youtube JSON REST API requests
Stars: ✭ 21 (-57.14%)
Mutual labels:  factory
hcv-color
🌈 Color model HCV/HCG is an alternative to HSV and HSL, derived by Munsell color system, usable for Dark and Light themes... 🌈
Stars: ✭ 44 (-10.2%)
Mutual labels:  model
typeorm-factory
Typeorm factory that makes testing easier
Stars: ✭ 28 (-42.86%)
Mutual labels:  factory
eSelection
Dynamic model selection library for SA-MP servers
Stars: ✭ 28 (-42.86%)
Mutual labels:  model
react-skeleton-loader
A react helper for skeleton loaders
Stars: ✭ 61 (+24.49%)
Mutual labels:  dummy
faker
Random fake data and struct generator for Go.
Stars: ✭ 67 (+36.73%)
Mutual labels:  factory
puppet-windows-hardening
Hardening Standalone Windows Server installations. LIST OF RULES NOT A PLUGIN
Stars: ✭ 12 (-75.51%)
Mutual labels:  dummy
powerform
A powerful form model.
Stars: ✭ 46 (-6.12%)
Mutual labels:  model

factoria Main npm

Simplistic model factory for Node/JavaScript, heavily inspired by Laravel's Model Factories.

Install

# install factoria
$ yarn add factoria -D
# install Faker as a peer dependency
$ yarn add @faker-js/faker -D

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 a Faker instance, which allows you to generate various random testing data.

Example:

const define = require('factoria').define

define('User', faker => ({
  id: faker.random.uuid(),
  name: faker.name.findName(),
  email: faker.internet.email(),
  age: faker.random.number({ min: 13, max: 99 })
}))

// TypeScript with generics
define<User>('User', faker => ({
  // A good editor/IDE should suggest properties from the User type
}))

2. Generate model objects

To generate model objects, import the factory and call it with the model's defined name. Following the previous example:

import factory from 'factoria'

// 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.'
  }
})

// TypeScript with generics
const user = factory<User>('User') // `user` is of type User
const users: User[] = factory<User>('User', 3) // `users` is of type User[]

Nested factories

factoria fully supports nested factories. For example, if you have a Role and a User model, the setup might look like this:

import factory from 'factoria'

factory.define('Role', faker => {
  name: faker.random.arrayElement(['user', 'manager', 'admin'])
}).define('User', faker => ({
  email: faker.internet.email(),
  role: factory('Role')
}))

Calling factory('User') will generate an object of the expected shape e.g.,

{
  email: '[email protected]',
  role: {
    name: 'admin'
  }
}

States

States allow you to define modifications that can be applied to your model factories. To create states, add an object as the third parameter of factory.define, where the key being the state name and its value the state's attributes. For example, you can add an unverified state for a User model this way:

factory.define('User', faker => ({
  email: faker.internet.email(),
  verified: true
}), {
  unverified: {
    verified: false
  }
})

State attributes can also be a function with Faker as the sole argument:

factory.define('User', faker => ({
  email: faker.internet.email(),
  verified: true
}), {
  unverified: faker => ({
    verified: faker.random.arrayElement([false]) // for the sake of demonstration
  })
})

You can then apply the state by calling the method states() with the state name, which returns the factoria instance itself:

const unverifiedUser = factory.states('unverified')('User')

You can also apply multiple states:

const fourUnverifiedPoorSouls = factory.states('job:engineer', 'unverified')('User', 4)

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 cup of tea:

{
  "jest": {
    "setupFilesAfterEnv": [
      "<rootDir>/test/setup.js"
    ]
  }
}

Then in test/setup.js you can import factoria and add the model definitions there.

Another approach is to have a wrapper module around factoria, have all models defined inside the module, and finally export factoria itself. You can then import the wrapper and use the imported object as a factoria instance (because it is a factoria instance), with all model definitions registered:

// tests/factory.js
import factory from 'factoria'

// define the models
factory.define('User', faker => ({}))
       .define('Group', faker => ({}))

// now export factoria itself
export default factory
// tests/user.spec.js
import factory from './factory'

// `factory` is a factoria function instance
const user = factory('User')

factoria itself uses this approach for its tests.

License

MIT © Phan An

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].