{{announcement.body}}
{{announcement.title}}

Let’s Fake it: Random Data Generation With Node and Faker.js

DZone 's Guide to

Let’s Fake it: Random Data Generation With Node and Faker.js

In this article, we discuss how to use Faker.js in order to generate data to test our Node.js applications.

· Web Dev Zone ·
Free Resource

fake-ducks-on-fence

Fake Data to Easily Test Your Application

Generally, we build our application with limited data sets and complete the functionality but end up finding ways to load bulk data for testing the function thoroughly.

It’s very difficult to get duplicate data for rows of a table and repeat the process to insert multiple rows.

You may also like: Generating and Mocking Data With MockNeat.

Here Comes Faker.js

Faker.js is truly a gem of a solution that takes away so much pain of generating testing data. Faker.js provides you a variety of fake data with Node. Let’s take an example of how to achieve this.

Let’s assume I have a user table with the following attributes:

  • UserID.

  • EmailID.

  • MobileNumber.

  • Password.

  • Role.

  • DOB.

  • Status.

And we want to enter 10 sample data rows for this table.

Step 1: Install With npm

npm i faker


Step 2: Create a Faker Test File

Open Visual Studio Code and create a new .js file called fakertest.js.

Step 3: Add Faker to the File

import faker library

var faker = require('faker');


Step 4: Generate Random Data

for (counter = 1; counter <= 10; counter++) {
console.log("------------Random Data: " + counter + "--------------");
console.log("UserID is: " + faker.random.uuid());
console.log("User Name is: " + faker.name.findName());
console.log("Email is: " + faker.internet.email());
  console.log("Mobile Number is: " + faker.phone.phoneNumber());
  console.log("Password is: " + faker.internet.password());
  console.log("Role is: " + faker.name.jobType());
  console.log("DOB is: " + faker.date.recent());
  console.log("Status is: " + faker.random.boolean());
}


Instead of console.log, you can insert the data into your database. In the next part, we will see how to insert the sample data using Faker.js to DynamoDB.

Refer to Faker's npm page for complete details.


Further Reading

Topics:
node.js ,web dev ,angular ,express ,backend ,server ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}