danibram / mocker-data-generator

A simplified way to generate masive mock data based on a schema, you can use the awesome fake/random data generators like (FakerJs, ChanceJs, CasualJs and RandExpJs)
https://danibram.github.io/mocker-data-generator/
MIT License
426 stars 45 forks source link
entity-generator fake mock-data schema typescript

mocker-data-generator Tweet

npm versionGitHub license

Linux Build statusWindows Build statusCodecov coverageCodecov coverage

GitHub licenseAwesome license

Support link

A simplified way to generate massive mock data based on a schema, using the awesome fake/random data generators like (FakerJs, ChanceJs, CasualJs and RandExpJs), all in one tool to generate your fake data for testing.

Now the library has been migrated 100% to typescript typing are included.

You can test online here: https://danibram.github.io/mocker-data-generator/

Getting started

Install the module and the awesome generator you want: npm install mocker-data-generator faker

Import it

var mocker = require('mocker-data-generator').default // (vanilla way)
var faker = require('faker')

// or

import mocker from 'mocker-data-generator' // (ES6 or Typescript way)
import * as faker from 'faker'

Then use it:

var user = {
    firstName: {
        faker: 'name.firstName()'
    },
    lastName: {
        faker: 'name.lastName()'
    },
    country: {
        faker: 'address.country()'
    },
    createdAt: {
        faker: 'date.past()'
    },
    username: {
        function: function () {
            return (
                this.object.lastName.substring(0, 5) +
                this.object.firstName.substring(0, 3) +
                Math.floor(Math.random() * 10)
            )
        }
    }
}
var group = {
    description: {
        faker: 'lorem.paragraph()'
    },
    users: [
        {
            function: function () {
                return this.generators.faker.random.arrayElement(this.db.user)
                    .username
            },
            length: 10,
            fixedLength: false
        }
    ]
}
var conditionalField = {
    type: {
        values: ['HOUSE', 'CAR', 'MOTORBIKE']
    },
    'object.type=="HOUSE",location': {
        faker: 'address.city()'
    },
    'object.type=="CAR"||object.type=="MOTORBIKE",speed': {
        faker: 'random.number()'
    }
}

// Using traditional callback Style

mocker()
    .addGenerator('faker', faker)
    .schema('user', user, 2)
    .schema('group', group, 2)
    .schema('conditionalField', conditionalField, 2)
    .build(function (error, data) {
        if (error) {
            throw error
        }
        console.log(util.inspect(data, { depth: 10 }))

        // This returns an object
        // {
        //      user:[array of users],
        //      group: [array of groups],
        //      conditionalField: [array of conditionalFields]
        // }
    })

// Using promises

mocker()
    .addGenerator('faker', faker)
    .schema('user', user, 2)
    .schema('group', group, 2)
    .schema('conditionalField', conditionalField, 2)
    .build()
    .then(
        data => {
            console.log(util.inspect(data, { depth: 10 }))
            // This returns an object
            // {
            //      user:[array of users],
            //      group: [array of groups],
            //      conditionalField: [array of conditionalFields]
            // }
        },
        err => console.error(err)
    )

// Synchronously

// This returns an object
// {
//      user:[array of users],
//      group: [array of groups],
//      conditionalField: [array of conditionalFields]
// }
var data = mocker()
    .addGenerator('faker', faker)
    .schema('user', user, 2)
    .schema('group', group, 2)
    .schema('conditionalField', conditionalField, 2)
    .buildSync()

console.log(util.inspect(data, { depth: 10 }))

NOTE: For the demo above you will also need to import util i.e. var util = require('util') or import util from 'util'

Documentation

Data generation goes with model based composed by generators, the generators can have access to the data generated and to the entity generated. Generators run synchronously, take care of the related entities!!

Methods

Schema definition

Every schema should contains the specified fields. Key can be 2 types:

Inside every value you can put:

Custom generators

It happens!Mocker now is independant of the generators so I hope this will give you more freedom. This is an example that you can check on the examples folder, where 2 generators are used:

    var mocker = require('../build/main').default
    var faker = require('faker')
    var Randexp = require('randexp')
    var util = require('util')

    var user = {
        firstName: {
            faker: 'name.firstName()'
        },
        notes: {
            randexp: /hello+ (world|to you)/
        }
    }

    mocker()
        .addGenerator('faker', faker)
        .addGenerator('randexp', Randexp, function (generator, input) {
            return new generator(input).gen()
        })
        .schema('user', user, 2)
        .build(function (error, data) {
            if (error) {
                throw error
            }
            console.log(util.inspect(data, { depth: 10 }))
        })

Optional fields

    {
        // Any generator
            // Faker
        [name of the generator injected]: 'path inside the generator'
            // If faker is injected with .addGenerator('faker', faker) then you can use:
        faker: 'random.arrayElement(db.users).userId'
            // Static
        static: 'any static field'
            // Function
        function: function (){ return /**/ }

        // With the virtual option
        virtual: true

    }

Data generation

Initialize mocker with the config, and then generate any entity with promises style, use generate function that accepts the name of the model and the amount of data to generate. Like the example:

mocker()
    .addGenerator('faker', faker)
    .schema('user', user, 2)
    .schema('group', group, 2)
    .schema('conditionalField', conditionalField, 2)
    .build(function(err, data) {
        console.log(util.inspect(data, { depth: 10 }))
        // This returns an object
        // {
        //      user:[array of users],
        //      group: [array of groups],
        //      conditionalField: [array of conditionalFields]
        // }
    })

You can also pass instead of the number, an object with the a config, from now {uniqueField}. If this field exists tells to the generator that instead of init a fixed length of data, generate an amount of data depending of the values of the field you will specify. You have 2 way to deal with this, check the examples See the output of this example:

//
// First way, using an 'values' embedded object
//

var cat = {
    name: {
        values: ['txuri', 'pitxi', 'kitty']
    }
}
var m = mocker()
    .addGenerator('faker', faker)
    .schema('cat', cat, 10)
    .schema('cat2', cat, { uniqueField: 'name' })
    .build(function(err, data) {
        console.log(util.inspect(data, { depth: 10 }))
    })

//
// Second way, without 'values' embedded.
//

var cat = {
    name: ['txuri', 'pitxi', 'kitty']
}
var m = mocker()
    .addGenerator('faker', faker)
    .schema('cat', cat, 10)
    .schema('cat2', cat, { uniqueField: 'name' })
    .build(function(err, data) {
        console.log(util.inspect(data, { depth: 10 }))
    })

eval Option (Beta):

In version >= 2.6.0, eval option was introduced to run mocker-data-generator like olders versions, so by default is running without eval: faker, chance, casual, hasMany, hasOne, db and self. This means that this methods loose habilities, when eval is not passed, but this are the speed results with eval active (old way) and without (new way)

faker eval old:  0.969ms
faker now:       0.215ms
chance eval old: 0.559ms
chance now:      0.099ms
casual eval old: 0.360ms
casual now:      0.026ms

More, Coming soon

Online API

You can visit the repo url here: https://github.com/danibram/mocker-api-tester

Or visit the api directly: https://mocker-api.herokuapp.com/

Development

Run npm install;npm run dev to watch the project, webpack compile the code automatically. Run npm build to build the normal and minified version.

Why not use json-schema-faker?

json-schema-faker is awesome and works really nice, but i need a simplified and fast way to generate mock data for my projects, so i created this.

Credits

I couldn't do this without this awesome libraries, so thanks to all:

License

Licensed under the MIT license. 2022