Gathering detailed insights and metrics for factory-girl
Gathering detailed insights and metrics for factory-girl
Gathering detailed insights and metrics for factory-girl
Gathering detailed insights and metrics for factory-girl
A factory library for node.js and the browser inspired by factory_girl
npm install factory-girl
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
552 Stars
323 Commits
87 Forks
15 Watching
2 Branches
2 Contributors
Updated on 25 Sept 2024
JavaScript (99.57%)
HTML (0.43%)
Cumulative downloads
Total Downloads
Last day
-6.1%
9,094
Compared to previous day
Last week
-3.2%
45,145
Compared to previous week
Last month
18.2%
193,950
Compared to previous month
Last year
-37.7%
1,924,652
Compared to previous year
2
factory-girl
is a factory library for Node.js and the browser that is inspired by Factory_girl. It works asynchronously and supports associations and the use of functions for generating attributes.
Node.js:
1npm install factory-girl
To use factory-girl
in the browser or other JavaScript environments, there are
builds for numerous module systems in the dist/
directory.
Refer to the tutorial for a gentle introduction of building a simple user factory.
Here's the crash course:
1const factory = require('factory-girl').factory; 2const User = require('../models/user'); 3 4factory.define('user', User, { 5 username: 'Bob', 6 score: 50, 7}); 8 9factory.build('user').then(user => { 10 console.log(user); // => User {username: 'Bob', score: 50} 11});
Define factories using the factory.define()
method.
For example:
1// Using objects as initializer 2factory.define('product', Product, { 3 // use sequences to generate values sequentially 4 id: factory.sequence('Product.id', (n) => `product_${n}`), 5 // use functions to compute some complex value 6 launchDate: () => new Date(), 7 // return a promise to populate data asynchronously 8 asyncData: () => fetch('some/resource'), 9}); 10factory.define('user', User, { 11 // seq is an alias for sequence 12 email: factory.seq('User.email', (n) => `user${n}@ymail.com`), 13 14 // use the chance(http://chancejs.com/) library to generate real-life like data 15 about: factory.chance('sentence'), 16 17 // use assoc to associate with other models 18 profileImage: factory.assoc('profile_image', '_id'), 19 20 // or assocMany to associate multiple models 21 addresses: factory.assocMany('address', 2, '_id'), 22 23 // use assocAttrs to embed models that are not persisted 24 creditCardNumber: factory.assocAttrs('credit_card', 'number', {type: 'masterCard'}), 25 26 // use assocAttrs or assocAttrsMany to embed plain json objects 27 twitterDetails: factory.assocAttrs('twitter_details'), 28});
1// Using functions as initializer 2factory.define('account', Account, buildOptions => { 3 let attrs = { 4 confirmed: false, 5 confirmedAt: null 6 }; 7 8 // use build options to modify the returned object 9 if (buildOptions.confirmedUser) { 10 attrs.confirmed = true; 11 attrs.confirmedAt = new Date(); 12 } 13 return attrs; 14}); 15 16// buildOptions can be passed while requesting an object 17factory.build('account', {}, {confirmed: true});
Options can be provided when you define a factory:
1factory.define('user', User, { foo: 'bar' }, options);
Alternatively you can set options for the factory that will get applied for all model-factories:
1factory.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 function should return the instance or throw an error. For asynchronous functions, it should return a promise that resolves with the instance or rejects with the error.
1factory.define('user', User, {foo: 'bar'}, { 2 afterBuild: (model, attrs, buildOptions) => { 3 return doSomethingAsync(model).then(() => { 4 doWhateverElse(model); 5 return model; 6 }); 7 }, 8 afterCreate: (model, attrs, buildOptions) => { 9 modify(model); 10 if ('something' === 'wrong') { 11 throw new Error; 12 } 13 maybeLog('something'); 14 return model; 15 } 16});
You can extend a factory using #extend
:
1factory.define('user', User, { username: 'Bob', expired: false }); 2factory.extend('user', 'expiredUser', { expired: true }); 3factory.build('expiredUser').then(user => { 4 console.log(user); // => User { username: 'Bob', expired: true }); 5});
#extend(parent, name, initializer, options = {})
The #extend
method takes the same options as #define
except you
can provide a different Model
using options.model
.
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 API response.
1factory.attrs('post').then(postAttrs => { 2 // postAttrs is a json representation of the Post model 3}); 4 5factory.attrs('post', {title: 'Foo', content: 'Bar'}).then(postAttrs => { 6 // builds post json object and overrides title and content 7}); 8 9factory.attrs('post', {title: 'Foo'}, {hasComments: true}).then(postAttrs => { 10 // builds post json object 11 // overrides title 12 // invokes the initializer function with buildOptions of {hasComments: true} 13});
You can use Factory#attrsMany
to generate a set of model attributes
1factory.attrsMany('post', 5, [{title: 'foo1'}, {title: 'foo2'}]).then(postAttrsArray => { 2 // postAttrsArray is an array of 5 post json objects 3 debug(postAttrsArray); 4});
Builds a new model instance that is not persisted.
1factory.build('post').then(post => { 2 // post is a Post instance that is not persisted 3});
The buildMany
version builds an array of model instances.
1factory.buildMany('post', 5).then(postsArray => { 2 // postsArray is an array of 5 Post instances 3});
Similar to Factory#attrs
, you can pass attributes to override or buildOptions.
Builds a new model instance that is persisted.
1factory.create('post').then(post => { 2 // post is a saved Post instance 3});
The createMany version creates an array of model instances.
1factory.createMany('post', 5).then(postsArray => { 2 // postsArray is an array of 5 Post saved instances 3});
Similar to Factory#attrs
and Factory#build
, you can pass attrs
to override and
buildOptions
. If you pass an array of attrs
then each element of the array will be
used as the attrs for a each model created.
If you can pass an array of attrs
then you can omit num
and the length of the array
will be used.
Destroys all of the created models. This is done using the adapter's destroy
method.
It might be useful to clear all created models before each test or testSuite.
Adapters provide support for different databases and ORMs. Adapters can be registered for specific models, or as the 'default adapter', which is used for any models for which an adapter has not been specified. See the adapter docs for usage, but typical usage is:
1const FactoryGirl = require('factory-girl'); 2const factory = FactoryGirl.factory; 3const adapter = new FactoryGirl.MongooseAdapter(); 4 5// use the mongoose adapter as the default adapter 6factory.setAdapter(adapter); 7 8// Or use it only for one model-factory 9factory.setAdapter(adapter, 'factory-name');
ObjectAdapter
is a simple adapter that uses const model = new MyModel()
,
model.save()
and model.destroy()
.
1factory.setAdapter(new factory.ObjectAdapter()); 2class MyModel { 3 save() { 4 // save the model 5 }, 6 destroy() { 7 // destroy the model 8 } 9} 10factory.define('model', MyModel);
You can create multiple factories which have different settings:
1let anotherFactory = new factory.FactoryGirl(); 2anotherFactory.setAdapter(new MongooseAdapter()); // use the Mongoose adapter
This module started out as a fork of
factory-lady, but the fork deviated quite a
bit. This module uses an adapter to talk to your models so it can support different ORMs
such as Bookshelf,
Sequelize,
JugglingDB, and
Mongoose (and doesn't use throw
for errors that might occur during save).
Version 4.0 is a complete rewrite with thanks to @chetanism.
Copyright (c) 2016 Chetan Verma.
Copyright (c) 2014 Simon Wade.
Copyright (c) 2011 Peter Jihoon Kim.
This software is licensed under the MIT License.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
2 existing vulnerabilities detected
Details
Reason
Found 6/24 approved changesets -- score normalized to 2
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More