Getting Started With Faker.js | A Detailed Guide

Getting Started With Faker.js | A Detailed Guide

Faker.js is all about faking everything. Well, we are not kidding. As you will go on with this article, you will get to know why it is necessary to use fake environments in software testing. As we always talk about and as described in the detailed article on “What Is Software Testing?”, if you are willing to deliver a smooth and efficient experience to your users, you must prioritize testing every bit of your tech products.

Now, you know how the enormous surge in the number of users and their demands are forcing the tech industry to make significant efforts to keep their CI/CD pipeline steady. And, one of the most effective ways to achieve that is automating most of the work. That’s why revolutionary steps are being taken to boost the level of no-code software development and testing.

Whenever there is a mention of no-code software testing, you must know that you have to conduct a lot of mocking as it is essential to achieve the best results. You can know everything about this fact here. However, let’s go to the depth of how Faker.js is effectively associated with all these.

What Is Faker.js?

Faker.js is a JavaScript library that helps you generate fake data that is a great necessity in developing or testing an application.

It is also defined as an npm module that mainly produces well-organized, realistic fake data for the smooth running of your automated tests. It helps you provide suitable inputs to data-driven tests. You just need to provide the input data to the system as a table of conditions. Then the conclusion of the system’s results depends on its output.

The best parts about using Faker.js are -

  • You can use it on both the server-side & browser side.
  • Fetching data doesn’t force you to use a database. Different types of data can easily be accessed using a simple script.
  • You get the flexibility to get as much data as you want by iterating with the help of a “for” loop.

Hence, Faker.js is truly beneficial in terms of generating necessary fake data for various areas like name, address, date, commerce, company, finance, image, or any random field.

How To Install Faker.js?

Installing Faker.js as a Dev Dependency using is a pretty simple one-step process that can even be completed using any of the widely popular package managers. We are jotting down three of them below.

npm install @faker-js/faker --save-dev


yarn add @faker-js/faker --dev


pnpm add @faker-js/faker --save-dev

When Faker.js is installed using the “node.js package manager”, it will automatically add it to the “Package.json” file present in your root project directory as npm dependencies. You can check it by yourself and the following declaration or something similar will confirm the same.

"dependencies": {
"faker": "^5.5.3"

Types of Data In Faker.js

Though we previously mentioned which types of data you can mock with the help of Faker.js, we are providing more details here. In the further portions of this article, you will get to know how to use Faker.js to generate many realistic versions of highly important data like -

  • Names
  • Addresses
  • Dates
  • Images
  • Phone
  • Internet
  • Animal
  • Vehicle
  • Git
  • Database
  • Datatype

These are some of the most crucial forms of data that can be mocked using Faker.js. Also, each one of them can further have more sub-data. For example, Git, the extremely important data for version control of any codebase, uses the following functions to get fake data -

  • branch
  • commitEntry
  • commitMessage
  • commitSha
  • shortSha

How To Generate Fake Data Using Faker.js?

As Faker.js has a diverse range of applications for different types of data, we are explaining them one by one.

Generating One Person’s Database With A JS Function

For generating a random first name, last name, job title, job area, phone number, and address of someone, we can proceed with importing the “faker” module first and then moving on with writing the respective functions. In that case, the “main.js” will look like this -

import { faker } from '@faker-js/faker';

let firstName =;
let lastName =;
let jobTitle =;
let prefix =;
let suffix =;
let jobArea =;
let phone =;
let address = faker.address();

console.log(`Employee: ${prefix} ${firstName} ${lastName} ${suffix}`);
console.log(`Job title: ${jobTitle}`);
console.log(`Job area: ${jobArea}`);
console.log(`Phone: ${phone}`);
console.log(`Address: ${address}`);

The above code will make the console look like this -

$ node names.js
Employee: John Harrison
Job Title: No-Code Tester
Job Area: Quality Assurance
Phone: 1-234-546-7654
Address: 45/8, Carter Road, Boston

Using Helper In Faker.js

The previous section shows how you can generate user data separately. But, when you need a long list of information about every user, creating these individual functions can never be an efficient practice. However, the best part about using Faker.js is that it provides you with an amazing helper feature that lets you generate multiple categories of user data at once. Let’s try to understand it with an example.

In the previous example, we had to use individual functions to generate each one of the names, job titles, job areas, phone, and addresses of an employee. On the other hand, just a contextualCard helper enables us to generate even more categories of such a user's database.

var userData = faker.helpers.contextualCard();

Due to the supremacy of helper in Faker.js, just this small bit of code is good enough to generate the following.

name: 'Alex',
username: 'Alex22',
avatar: '',
email: '',
dob: 1979-07-04T22:05:35.163Z,
phone: '1-456-654-2234',
address: {
street: 'Harley Plaza',
suite: 'Apt. 365',
city: 'West Bellford',
zipcode: '81108-3264',
geo: { lat: '28.6754', lng: '168.4709' }
website: '',
company: {
  name: 'Harvey, Harley and Benelli',
  catchPhrase: 'Organic explicit circuit',
   bs: 'implement back-end ROI'

Are you surprised to see so much data as the output of such a small code? Well, it will look even smaller in comparison to the createCard helper. Hence, let’s check out what that can do.

var fullUserData = faker.helpers.createCard();

Now, it’s time to see the output of this magical helper. (Some updates are made for more fun)

name: 'Albert Einstein',
username: 'AlbertEinstein999',
email: '',
address: {
streetA: 'Appleton Road',
streetB: '72654 Virginia Junctions',
 streetC: '2564 Light Fall Suite 007',
streetD: 'Apt. 512',
city: 'Rueckermouth',
state: 'New Mexico',
country: 'Burundi',
zipcode: '47621-9069',
geo: { lat: '63.4473', lng: '-103.9028' }
phone: '569.458.7845',
website: '',
company: {
 name: 'John, Ron and Harry',
 catchPhrase: 'Compatible human-resource contingency',
 bs: 'synergize dot-com ROI'
posts: [
words: 'A banyan tree',
sentence: 'He was sleeping peacefully.',
sentences: 'He was riding his bike. A chunk of gravel appeared suddenly.',
paragraph: 'Mankind is about having great qualities. The primary one is always helping others. Negative thoughts can bring disasters to this world'
words: 'A black car',
sentence: 'Wearing white dresses provides comfort in summer.',
sentences: 'Wear that shirt that I gifted you. It looks great on you.',
paragraph: 'Festivals means making the time more special for the family. Get some sweets and beverages home. Enjoy every moment with everyone.'
words: 'Hello world',
sentence: 'No-code is the future.',
sentences: 'Struggling with manual tests makes no sense. Get started with using no-code testing tools.',
paragraph: 'Technology is a blessing, my friend. You need to find out ways of using its positive side. Amazing rewards will be on your way soon.'
accountHistory: [
amount: '352.54',
date: 2012-02-01T18:30:00.000Z,
business: 'Fleet LLC',
name: 'Home Loan Account 7645',
type: 'payment',
account: '226598'
amount: '246.26',
date: 2012-02-01T18:30:00.000Z,
business: 'Jason, Daisy and Kristine',
name: 'Credit Card Account 5423',
type: 'invoice',
account: '2564784'
amount: '560.47',
date: 2012-02-01T18:30:00.000Z,
business: 'Jackson, Stela and Pamela',
name: 'Personal Loan Account 4576',
type: 'deposit',
account: '76552354'

Generating Random Values

You already know how important it becomes to generate and use random data such as any random number, random email, etc. at different points of tech operations. And, it is almost impossible to maintain huge databases or docs containing real values for such cases. Faker.js can save you there as mentioned below.

Let’s see how the “main.js” will look when you want to generate fake random values such as integers, uuids, or words.

import { faker } from '@faker-js/faker';
let number = faker.random.numeric();
let uuid = faker.datatype.uuid();
let word = faker.random.word();
let words = faker.random.words(6);

And, the output will look like -

$ node main.js
Controllable personalized message sending Corporate AI

Generate Language-Specific Fake Data Using Faker

Language specificity is a massive concern throughout the world. Though English is used as a bridge of communication in many places, not everyone likes it to be exclusive. Also, getting the flexibility to use tech products in any language that one is comfortable with turns out to be an awesome user experience.

And, Faker has remarkably taken care of this fact. From its version 2.0.0, Faker.js has been prioritizing localization support to enable you to generate fake data in multiple languages. Today, the constant improvement of that feature has made Faker.js compatible with generating mock/fake data in 50+ languages such as Russian, Korean, French, Turkish, Vietnamese, etc. Let’s try to explore this feature with a good example.

To get the output in Russian language, the “main.js” should be-

import { faker } from '@faker-js/faker/locale/ru';
let firstName =;
let lastName =;
console.log(`Pаботник: ${firstName} ${lastName}`);
let month =;
let recentDate =;
let rectentDate =;

The above code will generate the following output.

$ node main.js
Pаботник: Tom Goodwill

Generating Fake Data With JSON Server

It needs some steps to be followed to generate fake JSON data and write it to a file produced/served by the JSON server. Let’s check out the steps now.

Firstly, the json-server module needs to get installed by the following command -

$ npm i g json-server

Now, to generate fake JSON data, you need to write the following code in “main.js” -

import { faker } from '@faker-js/faker';
import fs from 'fs'

function generateUsers() {

 let users = []

 for (let id=1; id <= 100; id++) {

   let firstName =;
   let lastName =;
let address =;
   let email =;

       "id": id,
       "first_name": firstName,
       "last_name": lastName,
       "address": address,
       "email": email

 return { "data": users }

let dataObj = generateUsers();

fs.writeFileSync('data.json', JSON.stringify(dataObj, null, '\t'));

The above code will generate fake data for 100 users and write them to a data.json file. Now, when you start the JSON server, it serves data from the generated JSON file. To start the JSON server, the following line of code is the key.

$ json-server --watch data.json --port 3004

Now, if you want to retrieve the data of the user having Id 2, you can use the curl tool and get the following output -

$ curl localhost:3004/data/2/
 "id": 2,
 "first_name": "Bob",
 "last_name": "Henry",
"address": "Parker Street",
 "email": ""

You can also generate HTTP GET requests in JavaScript with the Node Request module. Start with installing the module by the following line -

$ npm i request

Now, the following “fetch_data.js” file will get the data of the users beginning with index 4(exclusive) and ending with index 8(inclusive).

import request from 'request';

request('http://localhost:3004/data?_start=4&_end=8', (err, resp, body) => {

   if (err) {
       console.error('request failed');
   } else {

The output will look like this -

$ node fetch_data.js
   "id": 5,
   "first_name": "Felipe",
   "last_name": "Gonalez",
"address": "Berlin",
   "email": ""
   "id": 6,
   "first_name": "Jeff",
   "last_name": "Bezos",
"address": "Mountain View",
   "email": ""
   "id": 7,
   "first_name": "Bill",
   "last_name": "Gates",
"address": "Sunnyvale",
   "email": ""
   "id": 8,
   "first_name": "Warren",
   "last_name": "Buffett",
"address": "Pennysylvania",
   "email": ""

Generating Fake Data Using A Faker CLI

Tests are not the only essential cause to generate contextual fake data. You may need to generate a lot of fake data even when you are not testing. For example, interacting with a command-line tool requires access to a database and that is always not possible. You may have to use fake names, phone numbers, addresses, product name, etc. for such needs. And, that is the scenario where you need to generate contextual fake data without any involvement of testing.

In those cases, using Faker CLI can solve your purpose. CLI is such a tool that totally justifies its name “Command-Line Interface Tool”. After knowing about all the amazing features of Faker.js, know about this awesome topping on that cake. This expert tool can easily be installed using npm. Just remember that the best practice about using it is that being a CLI tool, installing it globally is a much better move than installing it scoped to a single project. So, you can install it by using the following command.

$ npm install -g faker-cli

Usage of Faker CLI

Using Faker CLI makes the commands even shorter and easier to generate fake first names, last names, or phone numbers. Let’s check out the examples one by one.

Generating A Phone Number


faker-cli -p phoneNumber


"(546) 226-4569 x243"
Generating A First Name and A Last Name


faker-cli -n firstName




faker-cli -n lastName



Automate The Tests Now

No matter how many expert QA engineers you have in your team, it will take a hell lot of time to execute so many test cases manually. As we previously mentioned, technology is always evolving. Numerous applications are getting developed in different languages like Java, Python, etc. The modern world looks for every possible way to use the amazing benefits of tech products. And, it becomes extremely difficult to cope with such enormous demands of upgrades in technology with manual test suites.

However, like every other issue in this world, this can also be easily taken care of. Yes, we are talking about “Test Automation”, the savior for the tech world, developed by the tech world, and used by the same only. Automated tests can save such a significant amount of time that you can stay almost free to focus on new development works.

Also, the remarkable advancements in technology have created even simpler, better, and more efficient versions of test automation tools in the form of no-code ones. And, whenever it is about the supremacy of no-code testing tools, one of the top names is always PreFlight. Using this simple and marvelous browser extension can exempt you from worrying about learning about modern coding languages like TypeScript, data modelling library like Mongoose (used for MongoDB), SQL, GitHub, etc. You don’t even need any tutorial for learning the basic web page building parameters like HTML, CSS, API calls, etc. You can know about all the advantages of using it from the article “10 Amazing Software Testing Benefits From PreFlight In 2022”.

Hence, even if you want to execute all your tests with the fake data generated using Faker.js, let PreFlight take care of their smooth and top-notch performance. Its amazing AI can let you create and run tests within seconds and you can rerun & analyze those tests whenever you want. All you need to do is just book a demo and start experiencing it for free.


All these discussions have surely made you acknowledge the fact that how important Faker.js is in terms of mocking data for tests and others. Whenever you need huge databases, they can be generated with only a few lines of code. You already saw how Faker.js easily generates fake names, phone numbers, addresses, random values, language-specific data, etc. Also, it provides you with the flexibility to generate fake data with a JSON server and through the amazing CLI tool.

So, what more do you need? You have the efficient Faker.js to generate fake test data for free and you have the magical test automation tool PreFlight to take care of superfast test executions. Now, the only step you are left with is checking our supercool packages on our website and booking a demo. Also, if you get tempted by the zeal to know about new advancements in technology, become a regular follower of our blog page today.