Creating test dataset using Faker NPM package

We often get requirements for sample datasets for testing and development. It can be created manually if the required data size/application is small.

For a larger dataset, you need to find an automated solution. faker is an npm package that solves the exact problem.

You can generate any kind of data using faker. Let's see it in action by creating faqs data set of shape,

[
  {
    "id": "jkaj2390293",
    "question": "Question 1",
    "answer": "Answer 1",
    "author": {
      "name": "Param",
      "email": "param@example.com",
      "website": "https://jsmates.com"
    }
  },
  {
    "id": "jkaj2200295",
    "question": "Question 2",
    "answer": "Answer 2",
    "author": {
      "name": "Joshua",
      "email": "joshua@example.com",
      "website": "https://joshua.dev"
    }
  }
]

You can install the faker package using NPM,

npm install faker

Some examples of generating fake data using faker,

import faker from 'faker';

// Email
console.log(faker.internet.email());
// Website
console.log(faker.internet.url());
// Name
console.log(faker.name.findName());
// Title - Short text
console.log(faker.lorem.words());
// Description - Paragraphs
console.log(faker.lorem.paragraphs());

We will use the same to generate our sample data for faqs,

const createFaqs = (n = 10) => {
  const faqs = Array(n)
    .fill({}) // Create `n` items and fill empty object
    .map((_, id) => ({
      id, // array index value as the unique ID
      question: faker.lorem.words(),
      answer: faker.lorem.paragraphs(),
      author: {
        name: faker.name.findName(),
        email: faker.internet.email(),
        website: faker.internet.url()
      }
    }));

  return faqs;
};

// Create 100 faqs
const faqs = createFaqs(100);
console.log(faqs);

You can check the working example here,

We can improve this by adding a proper random ID for each sample item. We will see a package to generate a random unique ID.

Meanwhile, you can check our blog post on random unique ID generation using Math.random and timestamp here.

You can read the documentation of the package here.