{"id":22308800,"url":"https://github.com/ratson/factory-bot","last_synced_at":"2025-06-17T05:03:54.449Z","repository":{"id":46720091,"uuid":"141006596","full_name":"ratson/factory-bot","owner":"ratson","description":"Fork of https://github.com/aexmachina/factory-girl","archived":false,"fork":false,"pushed_at":"2021-09-28T16:50:29.000Z","size":748,"stargazers_count":34,"open_issues_count":2,"forks_count":17,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-05-19T20:46:39.906Z","etag":null,"topics":["hacktoberfest"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ratson.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-07-15T07:16:09.000Z","updated_at":"2025-04-13T05:16:12.000Z","dependencies_parsed_at":"2022-09-13T08:22:02.708Z","dependency_job_id":null,"html_url":"https://github.com/ratson/factory-bot","commit_stats":null,"previous_names":[],"tags_count":56,"template":false,"template_full_name":null,"purl":"pkg:github/ratson/factory-bot","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ratson%2Ffactory-bot","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ratson%2Ffactory-bot/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ratson%2Ffactory-bot/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ratson%2Ffactory-bot/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ratson","download_url":"https://codeload.github.com/ratson/factory-bot/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ratson%2Ffactory-bot/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260294454,"owners_count":22987622,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hacktoberfest"],"created_at":"2024-12-03T20:15:22.825Z","updated_at":"2025-06-17T05:03:54.423Z","avatar_url":"https://github.com/ratson.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# factory-bot\n\n`factory-bot` is a factory library for [Node.js](http://nodejs.org/). It works asynchronously and supports associations and the use of functions for generating attributes.\n\n## Installation\n\nNode.js:\n\n```bash\nnpm install factory-bot\n```\n\n## Usage\n\nRefer to [the tutorial](docs/tutorial.md) for a gentle introduction of building a simple\nuser factory.\n\nHere's the crash course:\n\n```javascript\nconst factory = require('factory-bot').factory;\nconst User    = require('../models/user');\n\nfactory.define('user', User, {\n  username: 'Bob',\n  score: 50,\n});\n\nfactory.build('user').then(user =\u003e {\n  console.log(user); // =\u003e User {username: 'Bob', score: 50}\n});\n```\n\n## Defining Models\n\nDefine models that have a constructor that takes an object with the attributes needed to\ninstantiate an instance of the model.\n\nFor example:\n\n```javascript\nclass User {\n    constructor(attrs = {}) {\n    this.attrs = Object.assign({\n      username: attrs.username || 'George',\n      score: attrs.score || 27,\n    }, attrs);\n  }\n}\n```\n\nThe factory methods will invoke this constructor during the construction of model objects.\n\n## Defining Factories\n\nDefine factories using the `factory.define()` method.\n\nFor example:\n\n```javascript\n// Using objects as initializer\nfactory.define('product', Product, {\n  // use sequences to generate values sequentially\n  id: factory.sequence('Product.id', (n) =\u003e `product_${n}`),\n  // use functions to compute some complex value\n  launchDate: () =\u003e new Date(),\n  // return a promise to populate data asynchronously\n  asyncData: () =\u003e fetch('some/resource'),\n});\nfactory.define('user', User, {\n  // seq is an alias for sequence\n  email: factory.seq('User.email', (n) =\u003e `user${n}@ymail.com`),\n\n  // use the chance(http://chancejs.com/) library to generate\n  // real-life like data.\n  // For repeatable results, call factory.chance.seed(\u003cvalue\u003e) first.\n  about: factory.chance('sentence'),\n\n  // use assoc to associate with other models\n  profileImage: factory.assoc('profile_image', '_id'),\n\n  // or assocMany to associate multiple models\n  addresses: factory.assocMany('address', 2, '_id'),\n\n  // use assocAttrs to embed models that are not persisted\n  creditCardNumber: factory.assocAttrs('credit_card', 'number', {type: 'masterCard'}),\n\n  // use assocAttrs or assocAttrsMany to embed plain json objects\n  twitterDetails: factory.assocAttrs('twitter_details'),\n});\n```\n\n```javascript\n// Using functions as initializer\nfactory.define('account', Account, buildOptions =\u003e {\n  let attrs = {\n    confirmed: false,\n    confirmedAt: null\n  };\n\n  // use build options to modify the returned object\n  if (buildOptions.confirmedUser) {\n    attrs.confirmed = true;\n    attrs.confirmedAt = new Date();\n  }\n  return attrs;\n});\n\n// buildOptions can be passed while requesting an object\nfactory.build('account', {}, {confirmed: true});\n```\n\n### Options\n\nOptions can be provided when you define a factory:\n\n```javascript\nfactory.define('user', User, { foo: 'bar' }, options);\n```\n\nAlternatively you can set options for the factory that will get applied for all model-factories:\n\n```javascript\nfactory.withOptions(options);\n```\n\nCurrently the supported options are:\n\n#### `afterBuild: function(model, attrs, buildOptions)`\n\nProvides a function that is called after the model is built.\nThe function should return the instance or a Promise for the instance.\n\n#### `afterCreate: function(model, attrs, buildOptions)`\n\nProvides a function that is called after a new model instance is saved. The function\nshould return the instance or throw an error. For asynchronous functions, it should return\na promise that resolves with the instance or rejects with the error.\n\n```javascript\nfactory.define('user', User, {foo: 'bar'}, {\n  afterBuild: (model, attrs, buildOptions) =\u003e {\n    return doSomethingAsync(model).then(() =\u003e {\n      doWhateverElse(model);\n      return model;\n    });\n  },\n  afterCreate: (model, attrs, buildOptions) =\u003e {\n    modify(model);\n    if ('something' === 'wrong') {\n      throw new Error;\n    }\n    maybeLog('something');\n    return model;\n  }\n});\n```\n\n### Extending Factories\n\nYou can extend a factory using `#extend`:\n\n```js\nfactory.define('user', User, { username: 'Bob', expired: false });\nfactory.extend('user', 'expiredUser', { expired: true });\nfactory.build('expiredUser').then(user =\u003e {\n  console.log(user); // =\u003e User { username: 'Bob', expired: true });\n});\n```\n\n### `#extend(parent, name, initializer, options = {})`\n\nThe `#extend` method takes the same options as `#define` except you\ncan provide a different `Model` using `options.model`.\n\n## Using Factories\n\n### Factory#attrs\n\nGenerates and returns model attributes as an object hash instead of the model instance.\nThis may be useful where you need a JSON representation of the model e.g. mocking an API\nresponse.\n\n```javascript\nfactory.attrs('post').then(postAttrs =\u003e {\n  // postAttrs is a json representation of the Post model\n});\n\nfactory.attrs('post', {title: 'Foo', content: 'Bar'}).then(postAttrs =\u003e {\n  // builds post json object and overrides title and content\n});\n\nfactory.attrs('post', {title: 'Foo'}, {hasComments: true}).then(postAttrs =\u003e {\n  // builds post json object\n  // overrides title\n  // invokes the initializer function with buildOptions of {hasComments: true}\n});\n```\n\nYou can use `Factory#attrsMany` to generate a set of model attributes\n\n```javascript\nfactory.attrsMany('post', 5, [{title: 'foo1'}, {title: 'foo2'}]).then(postAttrsArray =\u003e {\n  // postAttrsArray is an array of 5 post json objects\n  debug(postAttrsArray);\n});\n```\n\n### Factory#build\n\nBuilds a new model instance that is not persisted.\n\n```javascript\nfactory.build('post').then(post =\u003e {\n  // post is a Post instance that is not persisted\n});\n```\n\nThe `buildMany` version builds an array of model instances.\n\n```javascript\nfactory.buildMany('post', 5).then(postsArray =\u003e {\n  // postsArray is an array of 5 Post instances\n});\n```\n\nSimilar to `Factory#attrs`, you can pass attributes to override or buildOptions.\n\n### Factory#create(name, attrs, buildOptions)\n\nBuilds a new model instance that is persisted.\n\n```js\nfactory.create('post').then(post =\u003e {\n  // post is a saved Post instance\n});\n```\n\n### Factory#createMany(name, num, attrs, buildOptions = {})\n\nThe createMany version creates an array of model instances.\n\n```javascript\nfactory.createMany('post', 5).then(postsArray =\u003e {\n  // postsArray is an array of 5 Post saved instances\n});\n```\n\nSimilar to `Factory#attrs` and `Factory#build`, you can pass `attrs` to override and\n`buildOptions`. If you pass an array of `attrs` then each element of the array will be\nused as the attrs for a each model created.\n\n### Factory#createMany(name, attrs, buildOptions = {})\n\nIf you can pass an array of `attrs` then you can omit `num` and the length of the array\nwill be used.\n\n### Factory#cleanUp\n\nDestroys all of the created models. This is done using the adapter's `destroy` method.\nIt might be useful to clear all created models before each test or testSuite.\n\n## Adapters\n\nAdapters provide support for different databases and ORMs. Adapters can be registered for\nspecific models, or as the 'default adapter', which is used for any models for which an\nadapter has not been specified. See the adapter docs for usage, but typical usage is:\n\n```javascript\nconst FactoryBot = require('factory-bot');\nconst factory = FactoryBot.factory;\nconst adapter = new FactoryBot.MongooseAdapter();\n\n// use the mongoose adapter as the default adapter\nfactory.setAdapter(adapter);\n\n// Or use it only for one model-factory\nfactory.setAdapter(adapter, 'factory-name');\n```\n\n### ObjectAdapter\n\n`ObjectAdapter` is a simple adapter that uses `const model = new MyModel()`,\n`model.save()` and `model.destroy()`.\n\n```js\nfactory.setAdapter(new factory.ObjectAdapter());\nclass MyModel {\n  save() {\n    // save the model\n  },\n  destroy() {\n    // destroy the model\n  }\n}\nfactory.define('model', MyModel);\n```\n\n## Creating new Factories\n\nYou can create multiple factories which have different settings:\n\n```javascript\nlet anotherFactory = new factory.FactoryGirl();\nanotherFactory.setAdapter(new MongooseAdapter()); // use the Mongoose adapter\n```\n\n## History\n\nThis module is a fork or [factory-girl](https://github.com/aexmachina/factory-girl), which indeed a fork of\n[factory-lady](https://github.com/petejkim/factory-lady).\n\nThis fork keeps the same API as the original module, but with bugfixes and some extra features.\n\n## License\n\nThis software is licensed under the [MIT License](./LICENSE.txt).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fratson%2Ffactory-bot","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fratson%2Ffactory-bot","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fratson%2Ffactory-bot/lists"}