Generate fake data using JavaScript
When building an application, we often need data to show off to others how it works. Creating a database and filling it with some sample data is pretty annoying and time-consuming during building an awesome application.
There are many popular JavaScript libraries for generating mock data. In this article, we will be going through Faker.js which is the best-known library, but feel free to try the others too.
- Faker.js
- Chance.js
- Casual.js
Faker.js
Faker.js is the popular one among others inspired by Ruby’s Gem Faker. It supports both the browser and node.js environments. Pretty cool, huh?.
For instance, we can generate random some random user name and emailId as shown below,
var randomName = faker.name.findName(); // Caitlyn Kerluke
var randomEmail = faker.internet.email(); // Rusty@arne.info
Simple enough, right?. But it has a huge amount of API’s and the overall category list that faker.js can generate:
- address
- commerce
- company
- database
- date
- finance
- hacker
- image
- internet
- lorem
- name
- phone
- helpers
- random
I would encourage you to take a look at the documentation as well which helps you visualize the amount of data that comes out of this package.
Ok. Let’s take a use case where we need to get User Details from an API and display it in the profile page.
Since these are commonly generated data, faker gives access to helpers. Instead of picking one field here or there, these helpers can give a large amount of data that one would typically use in an application.
We will use the fakers.helpers.userCard() API to generate our fake user data.
That’s it. This is how we mock data using faker.js. It’s quick, clean and very simple to setup and no hassle at all.
From v2.0.0 faker.js also supports multiple localities with English as default language locale. We can also set locale as shown below,
// sets locale to en_IND (Indian English)
faker.setLocale("en_IND");
// or
faker.locale = "en_IND";
This package really helps to mock an API and return user information. I would encourage you to use faker.js for faster prototyping JavaScript application.
Thanks for reading. If you find this post useful, please hit the Clap button so this story can reach out to more readers.