Posted in

Getting Started with Faker.js in Cypress

Share this:

Getting Started with Faker

Test automation is great until you realize you keep feeding it the same static data over and over again. That’s where data generators come into play. One of my favorite tools for generating realistic fake data is faker.js. It helps you quickly generate random names, emails, phone numbers, and much more, making your test cases more robust and dynamic.

In this post, I’ll walk you through how to use faker.js together with Cypress, how to install everything, and how to build a simple test case for user registration.

Of course, Faker isn’t limited to JavaScript — you can use similar libraries in other popular languages like Python (Faker) or Java (java-faker) to generate realistic test data as well.

What is faker.js?

Faker.js is a JavaScript library that generates massive amounts of fake data that looks real. You can generate names, addresses, phone numbers, emails, passwords, even product descriptions, and much more. It’s an excellent tool for any kind of test automation where you need realistic but random data for your test scenarios.

If you want to dive into the full list of possibilities, head over to the faker.js documentation.

Installation

If you’re starting from scratch, you can initialize a new Cypress project like this:

npm init -y
npm install cypress --save-dev

After installation, you can open Cypress for the first time:

npx cypress open

Cypress will scaffold its default structure. You can now add your test files under cypress/e2e/.

For this example, I will assume you’re placing the test in cypress/e2e/register.cy.js.

First, you need to install the package. We will be using the actively maintained fork @faker-js/faker.

In your Cypress project folder, run:

npm install @faker-js/faker

Using Faker.js in Cypress

Now that Cypress and faker.js are installed, we can start using them together.

At the top of your test file, import faker:

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

The easiest way to explore what faker offers is through the official faker.js documentation. It lists all the available modules with detailed descriptions and examples. If you need a phone number, look into faker.phone.number(). For addresses, check faker.location. Once you get used to the structure, it becomes very intuitive. You simply ask yourself: “What kind of data do I need?” Then locate the relevant namespace and pick the function.

This way, you’re not guessing or googling each time. You systematically explore the documentation and quickly find

Understanding Faker.js Data Types

When you open the official faker.js repository or documentation, you’ll quickly notice that it offers much more than just names and emails. Faker is organized into namespaces, which group various categories of data. These are not just random names — each namespace serves a particular kind of data your tests might need.

Let’s go step-by-step through the most common ones: the correct method for your test data needs.

Person

Generates all kinds of personal data: full names, first and last names, genders, bios, job titles and more.
Example usage:

faker.person.fullName();
faker.person.jobTitle();

Location

Provides street addresses, cities, zip codes, states, countries, and even building numbers.
Example:

faker.location.streetAddress();
faker.location.city();
faker.location.country();

Date

Generates realistic dates: past, future, recent, or near future dates. Useful for things like birth dates or transaction timestamps.
Example:

faker.date.past();
faker.date.future();
faker.date.birthdate(); // very useful for generating valid dates of birth

Finance

Perfect for financial data: account numbers, transactions, IBANs, credit cards or cryptocurrency addresses.
Example:

faker.finance.accountNumber();
faker.finance.iban();
faker.finance.transactionDescription();

Commerce

Focused on e-commerce: product names, prices, departments, and product descriptions.
Example:

faker.commerce.productName();
faker.commerce.price();
faker.commerce.department();

Hacker

Fun but also useful for certain test scenarios (e.g., error messages, technical logs). It generates tech jargon that can simulate logs or system messages.
Example:

faker.hacker.phrase();

Number and String

If you just need flexible random numbers or strings, there are also helper methods for that:
Example:

faker.number.int({ min: 100, max: 999 });
faker.string.alphanumeric(10);

Real-Life Example – Sign Up Form Automation

To demonstrate how Faker works together with Cypress, I automated the user registration form using AAA Pattern on the website https://automationexercise.com.

In the test, I followed the AAA pattern, which stands for Arrange – Act – Assert. It’s a simple and widely used structure for writing clean and readable automated tests:

  • Arrange — set up everything needed before the test runs (test data, environment, navigation).
  • Act — perform the actual action being tested (e.g. filling out the form, clicking a button).
  • Assert — verify that the expected result has occurred (e.g. checking if the account was created).

Using AAA helps keep your tests well-organized and easy to maintain, especially when working with more complex scenarios.

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

describe('User Registration - AAA Pattern', () => {
  const user = {
    name: faker.person.fullName(),
    email: faker.internet.email(),
    password: faker.internet.password(10),
    day: '1',
    month: '5',
    year: '1990',
    firstName: faker.person.firstName(),
    lastName: faker.person.lastName(),
    address: faker.location.streetAddress(),
    city: faker.location.city(),
    state: faker.location.state(),
    zipcode: faker.location.zipCode(),
    mobile: faker.phone.number('+48 ### ### ###'),
    country: 'Canada'
  };

  it('should register a new user', () => {
    // Arrange
    cy.visit('https://automationexercise.com');
    cy.contains('Signup / Login').click();

    // Act
    cy.get('[data-qa="signup-name"]').type(user.name);
    cy.get('[data-qa="signup-email"]').type(user.email);
    cy.get('[data-qa="signup-button"]').click();

    cy.get('#id_gender1').check();
    cy.get('#password').type(user.password);
    cy.get('#days').select(user.day);
    cy.get('#months').select(user.month);
    cy.get('#years').select(user.year);
    cy.get('#newsletter').check();
    cy.get('#optin').check();
    cy.get('#first_name').type(user.firstName);
    cy.get('#last_name').type(user.lastName);
    cy.get('#address1').type(user.address);
    cy.get('#country').select(user.country);
    cy.get('[data-qa="city"]').type(user.city);
    cy.get('#state').type(user.state);
    cy.get('#zipcode').type(user.zipcode);
    cy.get('#mobile_number').type(user.mobile);
    cy.get('[data-qa="create-account"]').click();

    // Assert
    cy.contains('Account Created!').should('be.visible');
    cy.get('[data-qa="continue-button"]').click();
  });
});

Each time you run the test, a completely new user will be generated. This eliminates repetitive test data collisions, makes your test more realistic, and even helps you catch bugs that might only appear with certain inputs.

At the end of the test, I added a small step that saves the generated test data to a user.json file. This allows me to reuse the data later if needed, for example in follow-up tests or debugging.

Here is a sample output generated by this code:

{
  "email": "Marlene87@yahoo.com",
  "password": "rDGH2_bifvLczAn",
  "firstName": "Elaina",
  "lastName": "Kulas",
  "name": "Dallas Davis"
}

Using Faker.js Localization: Polish Example

By default, faker.js generates data in English, mostly following US conventions. But the library allows you to switch locales, so you can generate names, addresses, and phone numbers specific to many countries, including Poland.

Faker supports over 70 locales — including "pl" for Polish.

How to enable Polish localization:

When you import faker, you can configure the locale like this:

const { Faker } = require('@faker-js/faker');
const fakerPL = new Faker({ locale: pl });

Now all the data will be generated in Polish:

fakerPL.person.fullName(); // "Łukasz Nowak"
fakerPL.location.city(); // "Gdańsk"
fakerPL.phone.number(); // "504-123-456"
fakerPL.location.streetAddress(); // "ul. Lipowa 12"

What changes when you use localization?

  • Names — Polish first and last names.
  • Cities & addresses — cities and streets typical for Poland.
  • Phone numbers — formats that match Polish phone patterns.
  • Some finance data — e.g., IBAN starts with “PL”.

Why use localization in tests?

  • You avoid strange mixes like “John Smith living in Warszawa”.
  • You can simulate regional behaviors in your forms.
  • You can catch bugs related to specific alphabets (Polish letters: ą, ć, ę, ł, ń, ó, ś, ź, ż).
  • You ensure your app handles real-life data from your target market.

Now let’s take our registration test one step further and make the generated data even more realistic for Polish users. In our test we need to change below part:

const { Faker, pl } = require('@faker-js/faker');
import 'cypress-file-upload';

// Create Faker instance with Polish locale
const faker = new Faker({ locale: pl });

describe('User Registration - AAA Pattern', () => {
  
  const user = {
    name: faker.person.fullName(),
    email: faker.internet.email(),
    password: faker.internet.password(10),
    day: '1',
    month: '5',
    year: '1990',
    firstName: faker.person.firstName(),
    lastName: faker.person.lastName(),
    address: faker.location.streetAddress(),
    city: faker.location.city(),
    state: faker.location.state(),
    zipcode: faker.location.zipCode(),
    mobile: faker.phone.number('+48 ### ### ###'),
    country: 'United States' // for consistency with generated address
  }

Now the user.json file will be overwritten with data generated using the Polish locale. Let’s take a look at how it looks now:

{
  "email": "Platon.Wrona13@yahoo.com",
  "password": "B4QxvZ8pm7NxTtq",
  "firstName": "Janusz",
  "lastName": "Dobrzyński",
  "name": "Larysa Szewczyk"
}

It’s also worth mentioning that not all data types in Faker have full localization support. Some namespaces may not have translations or localized datasets for certain locales, including Polish. In such cases, Faker will either fall back to the default data or may even throw an error if a specific value isn’t defined. That’s something to keep in mind when working with localized test data, especially if you plan to rely on less common fields.

Example of error regarding method that is not supported in the Polish locale
Example: The jobTitle() method is not supported in the Polish locale and throws an error when called.

Postman and Faker

It’s worth noting that Postman actually uses Faker internally for its dynamic variables feature. Whenever you insert dynamic values in Postman using the $random... variables (like $randomFirstName, $randomEmail, $randomCity), Postman calls Faker behind the scenes to generate this data. You don’t need to import or install anything — it’s built right into Postman’s runtime.

Postman documentation screenshot
Offical Postman documentation about dynamic variables 

For example, in a request body you can simply write:

{
"name": "{{ $randomFullName }}",
"email": "{{ $randomEmail }}",
"city": "{{ $randomCity }}"
}

Each time the request runs, Postman will automatically fill in randomized values for these fields. This is especially useful when you’re building mock data, testing APIs, or creating data-driven requests without writing any code.

Summary

Faker.js is a simple but powerful way to bring your test automation to the next level. Instead of reusing the same data, you generate it on the fly. It keeps your tests fresh and increases your confidence that your application handles a variety of inputs correctly.

The best part is that it integrates perfectly with Cypress, which makes test automation not only effective but also easy to maintain.

If you haven’t yet, give it a try in your next Cypress project. Dynamic data generation is one of those small tricks that pays off very quickly when you’re building solid end-to-end tests.

via GIPHY

I am a Software Tester with over 7 years of experience, specializing in both manual and automated testing, with a strong focus on accessibility. Outside of work, I enjoy low-budget traveling and I’m a proud cat dad to Kimci and Świerzbinka. In my free time, I volunteer by running social media for a group that helps homeless cats find new homes.

Leave a Reply

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