Let’s Fake it: Random Data Generation With Node and Faker.js
Join the DZone community and get the full member experience.
Join For FreeFake 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
Opinions expressed by DZone contributors are their own.
Trending
-
Web Development Checklist
-
Transactional Outbox Patterns Step by Step With Spring and Kotlin
-
What to Pay Attention to as Automation Upends the Developer Experience
-
WireMock: The Ridiculously Easy Way (For Spring Microservices)
Comments