Generating Test Data in Cypress Tests

One of the limitations that I have come across with test automation, and specifically Cypress, in the past is the fact that it doesn’t have a built-in way to generate random test data. This became a blocker with Bytes as I needed to test a form which included a unique domain name field. This field was validated to check that the domain entered had not previously been registered in the staging db or with Microsoft Partner Centre. So, I couldn’t just enter ’testDomainName’ as it would only work once (if at all).

Faker.js

After a bit of digging I found faker.js. This is a library which includes a massive amount of fake data categorised by type. It isn’t just for Cypress, and is perfect for generating realistic but random test data.

All of the different methods that can be used are on github and once you’ve installed the library into the Cypress project then it is very easy to use. This is how I ended up using it for the domain input:

// cypress/integration/faker-test.js

import faker from 'faker'

describe('faker test', function(){
  it('faker test', function(){

    //Set a constant for valid domain name so that only 1 would be generated per test.
    //I used the 'time.recent' method as this produced a random string of numbers which 
    //seemed to work well.
    const validDomainName = {`validDomain${faker.time.recent}`}

    //Typed the randomly generated domain name into the input
    cy.get('input[data-qa="domain-name-input"]')
      .type(`test-domain-${validDomainName}`)

    //...

    //Later in the test once the form had been submitted, I was able to assert that the 
    //correct domain had been created using the same data.
    cy.get('div[data-qa="TenantDomainName"]')
      .should('contain', validDomainName)
    //If you wanted random data throughout the test then you could directly call the method at 
    //each point in the code and it would generate new data each time.
  })
})
    

There’s a lot more you can use faker for with Cypress, much of which I am yet to explore. But it works really well for applications like this. The library is well maintained and can be contributed to so there is constantly new categories of data being added.

Adam Clarkson

🔬 QA. ISTQB foundation certified tester