How to generate fake realistic test data in nodejs with faker.js

How to Generate Fake Test Data With Nodejs

When developing applications, testing is a crucial step to ensure that the application functions as expected under various scenarios. One common challenge during testing is the need for the data to simulate real-world conditions. To address this, fake test data is often used to populate databases, test APIs, or simulate user interactions.

However, It does not make sense to generate fake data manually, as it takes a long time, or to use real data, as it can violate the privacy and anonymity of individuals whose data is being used for testing purposes. Therefore, some packages developed and such package is @faker-js/faker. In this article, we will explore how to generate fake test data in Nodejs using the @faker-js/faker package.

Fake Data With Faker.js

Before we dive into generating fake data, ensure that you have Nodejs installed on your system. You can download it from nodejs.org. Then to get started, create a new Nodejs project or use an existing one. Navigate to your project directory in the terminal and run the following command to install the @faker-js/faker library:

npm install @faker-js/faker

Once the library is installed, you can start generating fake test data in your Nodejs application.

The Faker.js library provides a wide variety of fake data in various categories, including:

  • Location: This category generates fake addresses, such as street names, cities, states, and zip codes.
  • Commerce: This category generates fake commerce data, such as product names, prices, and descriptions.
  • Company: This category generates fake company names, bs phrases
  • Date: This category generates fake datetime data, such as dates, times, and timestamps.
  • Internet: This category generates fake internet data, such as email addresses, usernames, and passwords.
  • Person: This category generates fake names, such as first names, last names, and titles.
  • Phone: This category generates fake phone numbers, such as landlines, mobile phones, and fax numbers.
  • Image: This category generates fake image URLs, data URIs
  • Lorem: This category generates fake text data, such as paragraphs, sentences, and words.
  • Animal: This category generates fake species for different animals
  • Music: This category generates genres and songs.

Each category has its own methods for generating fake data. For example, in the person category, there are methods for generating a fake firstName, lastName, among others, while the location category has its own methods for generating fake streetAddress, city, and more.

const { faker } = require("@faker-js/faker");

const fakeName = faker.person.firstName();
const fakeEmail = faker.internet.email();
const fakeAddress = faker.location.streetAddress();

console.log(`Name: ${fakeName}`);
console.log(`Email: ${fakeEmail}`);
console.log(`Address: ${fakeAddress}`);

Customizing Locales

The Faker.js library also supports localization, which means that you can generate fake data that is specific to a particular language or culture.

To use localization in Faker.js, you need to import the pre-built Faker instances for other locales. For example, to generate fake data for German, you would use the following code:

import { fakerDE as faker } from '@faker-js/faker'

Or you can use the following import statement for generate data to Spain

import { fakerES as faker } from '@faker-js/faker'

For example, when you use the fakerDE instance to generate fake data, you will receive data that is specific to the German locale.

const { fakerDE } = require("@faker-js/faker");

const fakeName = fakerDE.person.fullName();
const fakeEmail = fakerDE.internet.email();

console.log(`Name: ${fakeName}`);
console.log(`Email: ${fakeEmail}`);

/* 
Name: Ramon Gehrig
Email: Willi_Sinnhuber75@gmail.com
*/

However, importing the entire library is not a good solution, as it increases the memory size used. Therefore, Faker.js also provides separate packages for each locale. You can import a package specifically for the German or Spain locale.

import { faker } from '@faker-js/faker/locale/de';
//or
import { faker } from '@faker-js/faker/locale/es';

Faker.js also supports 50 other locales, you can find supported locales here.

For advanced usage, you have an option: you can create a custom locale. This allows you to either combine locales and customize values of some properties of the locale.

Suppose you want to customize currencySymbol in your custom locale. Here’s how you can modify your customLocale to do that:

const { Faker, de_CH, de, en } = require("@faker-js/faker");

// Define your custom locale using LocaleDefinition
const customLocale = {
  title: "My custom locale",
  finance: {
    currencySymbol: "$",
  },
};

// Create a customFaker instance with the specified locale order
const customFaker = new Faker({
  locale: [customLocale, de, en],
});

console.log(customFaker.finance.currencySymbol());

In this example, we creates a custom Faker instance with the specified locale order. The locale property specifies the list of locales that should be used when generating data. In this case, the custom locale is first, followed by the de and en locales.

Building API

Now, let’s build a simple Expressjs API serves fake user data generated by @faker-js/faker. This simple API will have a route and whenever a request is made to this route, it will generate 10 users and send them to client. So, install the express.js with the following command.

npm install express

Then create an index.js file in your project directory to add codes for your API.

Our single route is /api/users that generates fake user data in JSON format. You can customize the number of users and the data fields as needed.

// Import required modules
const express = require("express");
const { faker } = require("@faker-js/faker");
const app = express();
const port = 3000;

// Define a route to generate fake user data
app.get("/api/users", (req, res) => {
  const numberOfUsers = 10; // Change this to the desired number of fake users
  const users = [];

  for (let i = 0; i < numberOfUsers; i++) {
    const user = {
      id: faker.string.uuid(),
      firstName: faker.person.firstName(),
      lastName: faker.person.lastName(),
      email: faker.internet.email(),
      createdAt: faker.date.past(),
    };
    users.push(user);
  }

  res.json(users);
});

// Start the Express.js server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

To start your Expressjs API, you can run the following command in your terminal:

node index.js

Now, your API will be available at http://localhost:3000/api/users. Open a web browser or use a tool like Postman to make GET requests to this endpoint, and you’ll receive an array of fake user data as shown in the following image:

Express API with faker.js

This was a simple example. You can use fake data to populate your databases or use it in your user interfaces for presentation or other purposes.

Conclusion

Generating fake test data with Nodejs and the Faker.js library is a powerful and convenient way to ensure that your software performs well with various fake data. Whether you’re testing a small feature or a complex application, having access to realistic test data can significantly improve the quality of your testing.

In this article, we have covered how to generate fake data in Nodejs with the faker.js library. In addition to this, we have built an simple express API to serve some fake users data over a users route.

If you want to check the faker.js library API guide, you can find here or if you want to learn more about testing in software development, you can check the following articles:

Thank you for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top