Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

ratson/factory-bot

Repository files navigation

factory-bot is a factory library forNode.js. It works asynchronously and supports associations and the use of functions for generating attributes.

Installation

Node.js:

npm install factory-bot

Usage

Refer tothe tutorial for a gentle introduction of building a simpleuser factory.

Here's the crash course:

constfactory=require('factory-bot').factory;constUser=require('../models/user');factory.define('user',User,{username:'Bob',score:50,});factory.build('user').then(user=>{console.log(user);// => User {username: 'Bob', score: 50}});

Defining Models

Define models that have a constructor that takes an object with the attributes needed toinstantiate an instance of the model.

For example:

classUser{constructor(attrs={}){this.attrs=Object.assign({username:attrs.username||'George',score:attrs.score||27,},attrs);}}

The factory methods will invoke this constructor during the construction of model objects.

Defining Factories

Define factories using thefactory.define() method.

For example:

// Using objects as initializerfactory.define('product',Product,{// use sequences to generate values sequentiallyid:factory.sequence('Product.id',(n)=>`product_${n}`),// use functions to compute some complex valuelaunchDate:()=>newDate(),// return a promise to populate data asynchronouslyasyncData:()=>fetch('some/resource'),});factory.define('user',User,{// seq is an alias for sequenceemail:factory.seq('User.email',(n)=>`user${n}@ymail.com`),// use the chance(http://chancejs.com/) library to generate// real-life like data.// For repeatable results, call factory.chance.seed(<value>) first.about:factory.chance('sentence'),// use assoc to associate with other modelsprofileImage:factory.assoc('profile_image','_id'),// or assocMany to associate multiple modelsaddresses:factory.assocMany('address',2,'_id'),// use assocAttrs to embed models that are not persistedcreditCardNumber:factory.assocAttrs('credit_card','number',{type:'masterCard'}),// use assocAttrs or assocAttrsMany to embed plain json objectstwitterDetails:factory.assocAttrs('twitter_details'),});
// Using functions as initializerfactory.define('account',Account,buildOptions=>{letattrs={confirmed:false,confirmedAt:null};// use build options to modify the returned objectif(buildOptions.confirmedUser){attrs.confirmed=true;attrs.confirmedAt=newDate();}returnattrs;});// buildOptions can be passed while requesting an objectfactory.build('account',{},{confirmed:true});

Options

Options can be provided when you define a factory:

factory.define('user',User,{foo:'bar'},options);

Alternatively you can set options for the factory that will get applied for all model-factories:

factory.withOptions(options);

Currently the supported options are:

afterBuild: function(model, attrs, buildOptions)

Provides a function that is called after the model is built.The function should return the instance or a Promise for the instance.

afterCreate: function(model, attrs, buildOptions)

Provides a function that is called after a new model instance is saved. The functionshould return the instance or throw an error. For asynchronous functions, it should returna promise that resolves with the instance or rejects with the error.

factory.define('user',User,{foo:'bar'},{afterBuild:(model,attrs,buildOptions)=>{returndoSomethingAsync(model).then(()=>{doWhateverElse(model);returnmodel;});},afterCreate:(model,attrs,buildOptions)=>{modify(model);if('something'==='wrong'){thrownewError;}maybeLog('something');returnmodel;}});

Extending Factories

You can extend a factory using#extend:

factory.define('user',User,{username:'Bob',expired:false});factory.extend('user','expiredUser',{expired:true});factory.build('expiredUser').then(user=>{console.log(user);// => User { username: 'Bob', expired: true });});

#extend(parent, name, initializer, options = {})

The#extend method takes the same options as#define except youcan provide a differentModel usingoptions.model.

Using Factories

Factory#attrs

Generates and returns model attributes as an object hash instead of the model instance.This may be useful where you need a JSON representation of the model e.g. mocking an APIresponse.

factory.attrs('post').then(postAttrs=>{// postAttrs is a json representation of the Post model});factory.attrs('post',{title:'Foo',content:'Bar'}).then(postAttrs=>{// builds post json object and overrides title and content});factory.attrs('post',{title:'Foo'},{hasComments:true}).then(postAttrs=>{// builds post json object// overrides title// invokes the initializer function with buildOptions of {hasComments: true}});

You can useFactory#attrsMany to generate a set of model attributes

factory.attrsMany('post',5,[{title:'foo1'},{title:'foo2'}]).then(postAttrsArray=>{// postAttrsArray is an array of 5 post json objectsdebug(postAttrsArray);});

Factory#build

Builds a new model instance that is not persisted.

factory.build('post').then(post=>{// post is a Post instance that is not persisted});

ThebuildMany version builds an array of model instances.

factory.buildMany('post',5).then(postsArray=>{// postsArray is an array of 5 Post instances});

Similar toFactory#attrs, you can pass attributes to override or buildOptions.

Factory#create(name, attrs, buildOptions)

Builds a new model instance that is persisted.

factory.create('post').then(post=>{// post is a saved Post instance});

Factory#createMany(name, num, attrs, buildOptions = {})

The createMany version creates an array of model instances.

factory.createMany('post',5).then(postsArray=>{// postsArray is an array of 5 Post saved instances});

Similar toFactory#attrs andFactory#build, you can passattrs to override andbuildOptions. If you pass an array ofattrs then each element of the array will beused as the attrs for a each model created.

Factory#createMany(name, attrs, buildOptions = {})

If you can pass an array ofattrs then you can omitnum and the length of the arraywill be used.

Factory#cleanUp

Destroys all of the created models. This is done using the adapter'sdestroy method.It might be useful to clear all created models before each test or testSuite.

Adapters

Adapters provide support for different databases and ORMs. Adapters can be registered forspecific models, or as the 'default adapter', which is used for any models for which anadapter has not been specified. See the adapter docs for usage, but typical usage is:

constFactoryBot=require('factory-bot');constfactory=FactoryBot.factory;constadapter=newFactoryBot.MongooseAdapter();// use the mongoose adapter as the default adapterfactory.setAdapter(adapter);// Or use it only for one model-factoryfactory.setAdapter(adapter,'factory-name');

ObjectAdapter

ObjectAdapter is a simple adapter that usesconst model = new MyModel(),model.save() andmodel.destroy().

factory.setAdapter(newfactory.ObjectAdapter());classMyModel{save(){// save the model},destroy(){// destroy the model}}factory.define('model',MyModel);

Creating new Factories

You can create multiple factories which have different settings:

letanotherFactory=newfactory.FactoryGirl();anotherFactory.setAdapter(newMongooseAdapter());// use the Mongoose adapter

History

This module is a fork orfactory-girl, which indeed a fork offactory-lady.

This fork keeps the same API as the original module, but with bugfixes and some extra features.

License

This software is licensed under theMIT License.

Packages

No packages published

Contributors38


[8]ページ先頭

©2009-2025 Movatter.jp