Using Faker for generating random data for your Cypress test

 

When you are automating a web form such as a registration ui, most of the time we need to be able to  run the test multiple times with unique inputs. In this blog post I will take you through how we can use faker  to generate random data for your Cypress test.

Assume that you have npm installed on your work environment, then we need to install faker with the command npm install faker

Once faker is installed the package.json will have an entry as below

"dependencies": {
"faker": "^5.5.3"
}

The next task is to call faker within your test script. To achieve this at the start of your test script declare the below line. This line will create a constant that can generate values using the faker into our test script.      

import { faker } from '@faker-js/faker';

The next task is to generate the required values. As seen from the below code, we can call the faker.name to generate first name,last name values and the faker.phone to generate the mobile numbers to our test. 

This way we can then pass the constants into the type command of Cypress to pass the required values for each test run. 

const firstName =faker.name.firstName();
const familyName =faker.name.firstName();
const mobileNumber =faker.phone.phoneNumber('966#######');


cy.get('#firstName').type(firstName);
cy.get('#familyName').type(familyName);

I hope this blog post will help you with your test automation efforts
when working with Cypress.

Comments