Testing applications seems easy…until the project gets bigger, and you need complete system testing along with unit and integration testing. But what happens when software testing is primarily data-driven and a chunk of test data doesn’t work? In that case, you need a large amount of mock data to test the system thoroughly.
So, to get a massive set of data, you might need to insert it into the database. What if you could get all the mock data you need to test the software using a simple JavaScript library?
Faker.js is one such popular JavaScript module. It generates large amounts of fake data to ease the process of data-driven testing.
In this post, I’ll help you get started with Faker.js. You’ll learn how to use it in your production system to generate different data types for testing purposes. Here’s a summary of what we’ll cover:
- Definition of Faker.js
- Features of Faker.js
- Installation instructions
- The types of data in Faker.js
- How to start generating data
- Data localization in Faker.js
- Usage of Helpers
- The Faker CLI
By the end of the post, you’ll have a solid understanding of what Faker.js is, why you’d want to use it, and how to get started in a practical and easy way.
What Is Faker.js?
Faker is an npm module whose sole purpose is to produce massive, well-organized, realistic fake data for testing applications. The best thing about Faker is that it doesn’t limit you to the server-side. You can use it on the browser side as well.
Faker is very helpful, especially for a tester implementing data-driven testing. In this situation, you’d pass input data in the system as a table of conditions. Then, based on the output received, you’d mark it as pass or fail.
You don’t need any database connection to fetch data. Instead, using a simple script, you can get different types of data. And by combining it with a for loop, you can iterate to get as much data as you want.
What Are the Features of Faker.js?
Let’s find out the types of realistic data that Faker can generate.
- You can use faker to generate data that is based on time (Present, future, past, etc.)
- Faker can generate localized realistic data containing region-specific phone numbers or pin codes.
- Faker can also generate virtual names with complete offline as well as online identification, along with addresses.
- You can create a virtual transaction, crypto addresses, and account details. Also in the case of a product, you can generate prices, names, and descriptions.
- Apart from all of the above, you can obviously generate numbers and strings using Faker.
Now that we have learned what Faker can do, let’s discuss how to install Faker.js in your JavaScript project.
How to Install or Add Faker.js in a JavaScript Project
Setting up Faker in your project is a one-step process. If you want to use it in your Node.js project, run a single command:
npm install faker --save
The command will install the Faker module and automatically add it to the “Package.json” file present in your root project directory as npm dependencies.
"dependencies": { "faker":"^5.5.3" }
Now, include the Faker module in your project using the built-in require function. You can start fetching data using available Faker API methods and helpers.
var faker = require('faker'); var randomPhoneNumber = faker.phone.phoneNumber(); var randomEmail = faker.internet.email();
Instead of Node, maybe you want to use Faker from within your browser. In that case, first, download the latest release file from GitHub and then include it using the script tag.
<script src = "faker.js" type = "text/javascript"></script> <script> var randomName = faker.name.findName(); var randomEmail = faker.internet.email(); var randomCard = faker.helpers.createCard(); </script>
Types of Data in Faker.js
Before you start using the Faker module, you also need to understand the data you can generate using Faker. Faker provides a wide range of data as the following objects:
names
Syntax
faker.name.firstName()
Output example
John Doe
addresses
Syntax
faker.address.city()
Output example
Sim City
images
Syntax
faker.image.dogs()
Output example
https://loremflickr.com/640/480/dogs
animal
Syntax
faker.animal.cat()
Output example
Mandarin fish
vehicle
Syntax
faker.vehicle.vehicle()
Output example
Mercedez Benz
phone
Syntax
faker.phone.phoneNumber()
Output example
+1 245-272-0145
lorem
Syntax
faker.lorem.paragraph()
Output example
“Non architecto nam unde sint…..”
internet
Syntax
faker.internet.domainName()
Output example
random-domainname.net
git
Syntax
faker.git.commitMessage()
Output example
feat: create products details page
finance
Syntax
faker.finance.amount()
Output example
Sets the locale currency and generates output like $3600.
date
Syntax
faker.date.past()
Output example
Sat Oct 15 2019 06:10:28 GMT-0700 (Pacific Daylight Time)
company
Syntax
faker.company.companyName()
Output example
Jones and son
commerce
Syntax
faker.commerce.product()
Output example
full sleeve shirt
database
Syntax
faker.database.engine()
Output example
ARCHIVE
datatype
Syntax
faker.datatype.uuid()
Output example
7b16ee12-935e-4agg-8381-b1k457cf0176
helpers
Syntax
faker.helpers.arrayElement(['a', 'b', 'c'])
Output example
b
Even each of the data categories mentioned above contains several functions to get different sub-data. For instance, git provides the following functions to get fake data:
- branch
- commitEntry
- commitMessage
- commitSha
- shortSha
So, if you want to get the fake branch name and commit message, you need to write a little code:
var branch=faker.git.branch(); var commitMsg=faker.git.commitMessage();
Generate Fake Data Using Faker.js
You’ve learned to install Faker in the Node project, and you understand the different types of data it provides. Now you can start using Faker in your project.
Let’s suppose you want fake vehicle data with details like vehicle name, color, manufacturer, model, type, and fuel. You can use the code below:
const faker = require('faker'); // Get fake vehicle data const vehicleName=faker.vehicle.vehicle(); // Aston Martin Element const color = faker.vehicle.color(); // mint green const model = faker.vehicle.model(); //Grand Caravan const manufacturer = faker.vehicle.manufacturer(); // Tesla const type = faker.vehicle.type(); // Passenger Van
What if you want mock data for a user with details like name, job title, and gender? You can use the code shown below. Once you generate the data, you can also format it the way you want, such as in JSON format data.
const faker = require('faker'); // Get fake user data const name=faker.name.findName(); const gender = faker.name.gender(); const title = faker.name.title(); const jobTitle = faker.name.jobTitle(); const jobDescriptor = faker.name.jobDescriptor();
const jsonData = JSON.stringify({ name, gender, title, jobTitle, jobDescriptor, }); console.log(jsonData);
Using Faker generates random data each time you execute the code. So if you want consistent data that doesn’t change in each execution, you need to set your own seed value.
faker.seed(100); const weekday = faker.date.weekday() console.log(weekday);
If you now run the code, you’ll notice that Faker data retrieved after setting seed value gives the same data all the time.
Get Language-Specific Mock Data Using Faker
Do you want fake data in a language other than English? Faker also has a feature that lets you switch between locales easily.
Starting with version 2.0.0, Faker.js added localization support to provide fake data in multiple languages. Currently, Faker has English as the default locale and supports more than 50 localities. These include Korean, Azerbaijani, French, Farsi/Persian, Turkish, Russian, and Vietnamese.
So, if you want to change your locale, you need to set a new locale value.
faker.locale = 'fr'
Now, if you generate data below this line using Faker, you’ll get fake data only in French.
Here’s another way you can include the locale data for a specific set of locales:
// loads only fr locale
const faker = require('faker/locale/fr');
Instead of loading all locale data, the above code loads data for the specified locale only.
Use Helper in Faker
Another important feature that Faker provides is a helper. Currently, if you need user data, you can use faker.name. If you need financial details, you can use faker.finance. And if you need address data, you can use faker.address.
This means you need to call different objects for different data. Here comes a helper that helps you get multiple categories of data at once, easily! Using a helper gives you a large amount of data, combining multiple objects like finance, address, and name in one object.
For example, you want basic user details: name, phone, email, address, company, and website. Instead of using multiple objects for each type of data, use a contextualCard helper that’ll provide all important data easily.
var userData = faker.helpers.contextualCard(); console.log(userData);
If you run the above code, you’ll get the user card data shown below.
{ name: 'Karianne', username: 'Karianne41', avatar: 'https://cdn.fakercloud.com/avatars/isaacfifth_128.jpg', email: '[email protected]', dob: 1984-11-21T20:07:44.163Z, phone: '1-362-841-8508', address: { street: 'Ledner Plaza', suite: 'Apt. 510', city: 'West Wilford', zipcode: '81108-3264', geo: { lat: '35.8846', lng: '158.4108' } }, website: 'lucius.net', company: { name: 'Harvey, Gusikowski and Daniel', catchPhrase: 'Organic explicit circuit', bs: 'implement back-end ROI' } }
Now, suppose you want more user data on a card. You can use a different helper, createCard. It fetches a large amount of data, including financial, posts, and account history.
var fullUserData = faker.helpers.createCard(); console.log(fullUserData);
{ name: 'Amanda Gleason', username: 'Alvena.Labadie', email: '[email protected]', address: { streetA: 'Ruecker Turnpike', streetB: '39394 Virginia Junctions', streetC: '2836 Mueller Fall Suite 024', streetD: 'Apt. 770', city: 'Rueckermouth', state: 'New Mexico', country: 'Burundi', zipcode: '47621-9069', geo: { lat: '63.4473', lng: '-103.9028' } }, phone: '926.453.3765', website: 'tomas.org', company: { name: 'Mohr, Wiza and Huels', catchPhrase: 'Compatible human-resource contingency', bs: 'synergize dot-com ROI' }, posts: [ { words: 'ex consequuntur tenetur', sentence: 'Hic sed repellat nesciunt minus.', sentences: 'Nam ipsam est nam sed dolores consequatur rerum est. Perferendis quo neque accusamus ea voluptate qui deleniti.', paragraph: 'Aut esse error consequatur id nemo sit sapiente. Eos tempora ipsam. Labore sunt explicabo cumque autem exercitationem animi qui aut. Et veritatis sunt ratione hic omnis aut. Omnis recusandae itaque.' }, { words: 'sed architecto non', sentence: 'Sed eaque at aut quo fugiat odit nostrum fugiat.', sentences: 'Dolore officia error. Perspiciatis libero sunt et aut provident et maiores reiciendis. Voluptatem saepe corporis ducimus quod id autem. Quibusdam corrupti veniam harum.', paragraph: 'Earum ullam non. Soluta et quisquam. Blanditiis qui temporibus quia. Tenetur eos sit ut commodi. In id nesciunt architecto ullam est rerum.' }, { words: 'ut recusandae quis', sentence: 'Ex qui rerum libero.', sentences: 'In ipsa id aliquam. Aut non ullam ut consequuntur excepturi. Dolorum porro ut aut illum. Ut sequi adipisci et ad harum. Non molestiae aliquam est soluta.', paragraph: 'Quia non sint ea tenetur et enim qui. Quis itaque sunt deserunt dolores dolorem et in assumenda. Exercitationem sapiente distinctio voluptas sapiente assumenda sit autem hic. Blanditiis culpa accusantium voluptate vel non corrupti repellendus et. Qui aut quos. Qui molestias tenetur consequatur suscipit qui.' } ], accountHistory: [ { amount: '298.47', date: 2012-02-01T18:30:00.000Z, business: 'Feest LLC', name: 'Home Loan Account 8042', type: 'payment', account: '41153089' }, { amount: '357.26', date: 2012-02-01T18:30:00.000Z, business: 'Ullrich, Deckow and Kautzer', name: 'Credit Card Account 6312', type: 'invoice', account: '14080195' }, { amount: '684.47', date: 2012-02-01T18:30:00.000Z, business: 'Johnston, Stark and Pouros', name: 'Personal Loan Account 5212', type: 'deposit', account: '84556257' } ] }
Using Faker CLI
You might also need to generate fake data in a context other than when you’re testing an application. Maybe you’re interacting with some command-line tool and you need a couple of fake names, addresses or dates. What should you do?
In this case, you can use Faker CLI. As the name suggests, this is a CLI (command-line interface tool) to generate fake data. Faker CLI is essentially a wrapper over Faker.js, and you install it using npm as well. Since this is a CLI tool, you’ll want to install it globally, rather than installing it scoped to a single project:
$ npm install -g faker-cli
Then, you just have to use it. Here are a few examples.
Generate a Zip Code
faker-cli -a zipCode
Result:
"76949-5596"
Generate a First Name and Last Name
Generating a first name:
faker-cli -n firstName
Result:
"Jevon"
Gnerating a last name:
faker-cli -n lastName
Result:
"Greenholt"
Generate a Phone Number
faker-cli -p phoneNumber
Results:
"(739) 113-3200 x243"
Automate Your Testing
To reduce the effort required for repetitive work, it makes sense to use automation. Likewise, if you want to use Faker at scale in your project, you might want to automate the process of testing using fake data.
How can you do that? Testim’s test automation platform is one such solution. Testim also provides insights that you can analyze and scale at any time efficiently.
Testim Automate is a fast and flexible solution with AI-powered end-to-end tests. It also lets you run custom code inside or outside the browser. That way, you can adapt your test to suit nearly any situation.
The good part is you can start Testim for free and use Testim’s custom JS step to pull in data from Faker.js. Even when you want to reuse your custom code across tests, you can save it for reuse, like a function in a programming language.
With Testim, you also get the built-in JavaScript editor that uses Monaco open-source to provide fast, robust syntax checking and code completion.
Use Faker to Mock Massive Data
To sum up, Faker can save you a lot of effort and time. It does this by providing massive fake data using a few lines of code. Instead of writing specific code for mock data and then inserting it into a database, you can use Faker to test your system.
With different types of data, Faker also gives you flexible and organized input. Not to mention, Faker is free and open source.
There’s also Faker-CLI, a command-line that offers a simple wrapper around Faker.js. With the CLI tool, you can quickly and easily generate fake names, addresses, phone numbers and much more. The CLI tool allows you to generate fake test data in a variety of contexts, and it’s particularly useful for automations of all kinds. Also, since it’s a CLI tool installed globally, its usage isn’t restricted to JavaScript: instead, you can use it from any of your favorite shells.