How to generate various fake data using JavaScript

Written by on April 3, 2015

How to generate various fake data using JavaScript

There are times when you need to test your application using a massive amount of fake data. This way you can leverage your application against a large set of data, all inside a safe test environment. Every programming or scripting language has a way of achieving this; JavaScript is one of them.

Probably best-known faker JavaScript framework is Faker.js, I’ll review it first. Other will come later, one by one. This way you can decide what other frameworks can or can’t do, and are they a better choice for you.

Note: If this tutorial was helpful, you need further clarification, something is not working or you have a request for another Ionic post? Furthermore, leave me a comment below if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com. Thanks and have a nice day!

Article will cover these frameworks:

1. Faker.js


Official Site
GitHub

Faker.js is probably the best known JavaScript faker framework inspired by Ruby’s Gem Faker and Perl’s Data::Faker. Faker.js makes it simple to create any amount of fake data within your browser or on the server using Node.js. You will be able to generate information like names, addresses, phone numbers, internet related data, companies, images, lorem ipsum, dates, random numbers, financial data, etc.

Usage

Faker.js don’t require additional dependencies, just include it in your application, like this:

<script src="http://marak.com/faker.js/js/faker.js"></script>

Simple Example

Both Node.js and browser versions work out of the box:

/* Browser example */

var randomName = faker.name.findName(); // Caitlyn Kerluke
var randomEmail = faker.internet.email(); // Rusty@arne.info
var randomCard = faker.helpers.createCard(); // random contact card containing many properties

/* Node.js example */

var faker = require('./faker');

var randomName = faker.name.findName(); // Rowan Nikolaus
var randomEmail = faker.internet.email(); // Kassandra.Haley@erich.biz
var randomCard = faker.helpers.createCard(); // random contact card containing many properties

Localization

Localization is also supported, by default it supports 27 different language definition packs. The default language is set to English, so you don’t need to change it if you’re not required to do so.

Setting a new locale is simple as this:

// sets locale to Germany
faker.locale = "de";

API

Supported API offers a wide range of available categories (options):

[spoiler title=” Click here if you want to see available API options.”]

  • Name
    • firstName
    • lastName
    • findName
    • prefix
    • suffix
  • Address
    • zipCode
    • city
    • cityPrefix
    • citySuffix
    • streetName
    • streetAddress
    • streetSuffix
    • secondaryAddress
    • county
    • country
    • state
    • stateAbbr
    • latitude
    • longitude
  • Phone
    • phoneNumber
    • phoneNumberFormat
    • phoneFormats
  • Internet
    • avatar
    • email
    • userName
    • domainName
    • domainSuffix
    • domainWord
    • ip
    • userAgent
    • color
    • password
  • Company
    • suffixes
    • companyName
    • companySuffix
    • catchPhrase
    • bs
    • catchPhraseAdjective
    • catchPhraseDescriptor
    • catchPhraseNoun
    • bsAdjective
    • bsBuzz
    • bsNoun
  • Image
    • image
    • avatar
    • imageUrl
    • abstract
    • animals
    • business
    • cats
    • city
    • food
    • nightlife
    • fashion
    • people
    • nature
    • sports
    • technics
    • transport
  • Lorem
    • words
    • sentence
    • sentences
    • paragraph
    • paragraphs
  • Helpers
    • randomNumber
    • randomize
    • slugify
    • replaceSymbolWithNumber
    • shuffle
    • mustache
    • createCard
    • contextualCard
    • userCard
    • createTransaction
  • Date
    • past
    • future
    • between
    • recent
  • Random
    • number
    • array_element
    • object_element
  • Finance
    • account
    • accountName
    • mask
    • amount
    • transactionType
    • currencyCode
    • currencyName
    • currencySymbol
  • Hacker
    • abbreviation
    • adjective
    • noun
    • verb
    • ingverb
    • phrase
  • Definitions
    • name
    • address
    • company
    • lorem
    • hacker
    • phone_number
    • finance
    • internet

[/spoiler]

Helpers

One of the interesting things about Faker.js are helper methods that let you create bulk fake data using the single API methods. They will make your life easier, instead of working with single fields Faker.js will generate prefilled objects using a single helper method.

var contextualCard = faker.helpers.contextualCard();
console.log(contextualCard);

var userCard = faker.helpers.userCard();
console.log(userCard);

var transaction = faker.helpers.createTransaction();
console.log(transaction );

var card = faker.helpers.createCard();
console.log(card);

Working example

This example uses Ionic Framework and AngularJS though it’s easily readable:

Demo

Embedded working example:

Ionic Framework generate fake data

2. Casual.js

Official Site
GitHub

Casual.js is a relative newcomer heavily inspired by Faker.js. It supports a very similar set of data, in addition, you’ll find support for Colors, Dates, and Numbers. Even better, if something is missing, you can easily define custom generators.

Still I don’t like few things about Casual.js. By default, instead of functions, Casual.js uses object properties to represent randomly generated data. For example, casual.name is not a function but a property with a value that changes each time you access it.

Note: This is not the case anymore; a recent change brought generators functions support. Unfortunately, I missed this feature completely; it's described near the documentation end.

Another thing is Node.js dependency, browser auto/manual instantiation is not supported.

Installation

npm install casual

Simple Example

Only Node.js usage is supported:

/* Node.js example */

var casual = require('casual');

var randomName = casual.full_name       // 'Kadin Torphy'
var randomEmail = casual.email          // 'Josue.Hessel@claire.us'
var randomCard = casual.card_data       // { type: 'MasterCard', number: '5307558778577046', exp: '04/88', holder_name: 'Jaron Gibson' }

Localization

Localization is also supported, from my calculation it supports six different languages. The default locale is en_US, so you don’t need
to change it if you’re not required to do so.

Setting a new locale is simple as this:

// sets locale to Russia
var casual = require('casual').ru_RU;

API

Supported API offers a wide range of available categories (options):

[spoiler title=” Click here if you want to see available API options.”]

// Address

casual.country          // 'United Kingdom' <br/>
casual.city             // 'New Ortiz chester' <br/>
casual.zip              // '26995' <br/>
casual.street           // 'Jadyn Islands' <br/>
casual.address          // '6390 Tremblay Pines Suite 784' <br/>
casual.address1         // '8417 Veda Circles'<br/>
casual.address2         // 'Suite 648' <br/>
casual.state            // 'Michigan' <br/>
casual.state_abbr       // 'CO' <br/>
casual.latitude         // 90.0610 <br/>
casual.longitude        // 180.0778 <br/>
casual.building_number  // 2413 <br/><br/>

// Text<br/><br/>

casual.sentence               // 'Laborum eius porro consequatur.'<br/>
casual.sentences(n = 3)       // 'Dolorum fuga nobis sit natus consequatur. Laboriosam sapiente. Natus quos ut.'<br/>
casual.title                  // 'Systematic nobis'<br/>
casual.text                   // 'Nemo tempore natus non accusamus eos placeat nesciunt. et fugit ut odio nisi dolore non ... (long text)'<br/>
casual.description            // 'Vel et rerum nostrum quia. Dolorum fuga nobis sit natus consequatur.'<br/>
casual.short_description      // 'Qui iste similique iusto.'<br/>
casual.string                 // 'saepe quia molestias voluptates et'<br/>
casual.word                   // 'voluptatem'<br/>
casual.words(n = 7)           // 'sed quis ut beatae id adipisci aut'<br/>
casual.array_of_words(n = 7)  // [ 'voluptas', 'atque', 'vitae', 'vel', 'dolor', 'saepe', 'ut' ]<br/>
casual.letter                 // 'k'<br/><br/>

// Internet<br/><br/>

casual.ip           // '21.44.122.149'<br/>
casual.domain       // 'darrion.us'<br/>
casual.url          // 'germaine.net'<br/>
casual.email        // 'Josue.Hessel@claire.us'<br/>
casual.user_agent   // 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0'<br/><br/>

// Person<br/><br/>

casual.name            // 'Alberto'<br/>
casual.username        // 'Darryl'<br/>
casual.first_name      // 'Derek'<br/>
casual.last_name       // 'Considine'<br/>
casual.full_name       // 'Kadin Torphy'<br/>
casual.password        // '(205)580-1350Schumm'<br/>
casual.name_prefix     // 'Miss'<br/>
casual.name_suffix     // 'Jr.'<br/>
casual.company_name    // 'Cole, Wuckert and Strosin'<br/>
casual.company_suffix  // 'Inc'<br/>
casual.catch_phrase    // 'Synchronised optimal concept'<br/>
casual.phone           // '380 82 790 25 92'<br/><br/>

// Numbers<br/><br/>

casual.random                            // 0.7171590146608651 (core generator)<br/>
casual.integer(from = -1000, to = 1000)  // 632<br/>
casual.double(from = -1000, to = 1000)   // -234.12987444<br/>
casual.array_of_digits(n = 7)            // [ 4, 8, 3, 1, 7, 6, 6 ]<br/>
casual.array_of_integers(n = 7)          // [ -105, -7, -532, -596, -430, -957, -234 ]<br/>
casual.array_of_doubles(n = 7)           // [ -866.3755785673857, -166.62194719538093, ...]<br/><br/>

// Date<br/><br/>

casual.unix_time                    // 659897901<br/>
casual.moment                       // moment.js object see http://momentjs.com/docs/<br/>
casual.date(format = 'YYYY-MM-DD')  // '2001-07-06' (see available formatters http://momentjs.com/docs/#/parsing/string-format/)<br/>
casual.time(format = 'HH:mm:ss')    // '03:08:02' (see available formatters http://momentjs.com/docs/#/parsing/string-format/)<br/>
casual.century                      // 'IV'<br/>
casual.am_pm                        // 'am'<br/>
casual.day_of_year                  // 323<br/>
casual.day_of_month                 // 9<br/>
casual.day_of_week                  // 4<br/>
casual.month_number                 // 9<br/>
casual.month_name                   // 'March'<br/>
casual.year                         // 1990<br/>
casual.timezone                     // 'America/Miquelon'<br/><br/>

// Payments<br/><br/>

casual.card_type            // 'American Express'<br/>
casual.card_number(vendor)  // '4716506247152101' (if no vendor specified then random)<br/>
casual.card_exp             // '03/04'<br/>
casual.card_data            // { type: 'MasterCard', number: '5307558778577046', exp: '04/88', holder_name: 'Jaron Gibson' }<br/><br/>

// Misc<br/><br/>

casual.country_code    // 'ES'<br/>
casual.language_code   // 'ru'<br/>
casual.locale          // 'hi_IN'<br/>
casual.mime_type       // 'audio/mpeg'<br/>
casual.file_extension  // 'rtf'<br/><br/>

// Colors<br/><br/>

casual.color_name       // 'DarkOliveGreen'<br/>
casual.safe_color_name  // 'maroon'<br/>
casual.rgb_hex          // '#2e4e1f'<br/>
casual.rgb_array        // [ 194, 193, 166 ]<br/>

[/spoiler]

Helpers

Casual.js supports helper methods just like Faker.js though is somewhat different fashion. Where Faker.js provides helpers for predefined objects, Casual.js provides “do it yourself” approach:

var custom1 = casual.populate('{{email}} {{first_name}}'); // 'Dallin.Konopelski@yahoo.com Lyla'
console.log(custom1);

var custom2 = casual.populate_one_of(['{{first_name}}', '{{last_name}} {{city}}']);
console.log(custom2);

var custom3 = casual.random_value({ a: 1, b: 3, c: 42 }); // val will be equal 1 or 3 or 42
console.log(userCard);

Continue Reading

Categories

3 thoughts on “How to generate various fake data using JavaScript”

  1. It’s going to be ending of mine day, but before
    finish I am reading this fantastic piece of writing to increase my
    know-how.

  2. Thank you for a nice writeup! Much needed because of this regrettable side-effect of OSS, a myriad of libraries doing almost exactly the same thing.

Leave a Reply