Faking It At Work: Testing with Javascript and Faker

Posted: 2020-12-10

Get to work!

As known as: Generating test data.

Here at Process IQ we are obsessed with automated testing to ensure our customers get top notch products and service. We do all of them: unit testing, integration testing, regression testing and performance testing. Some times we even test our test tools to ensure that they are good at testing (whew! that was a mouthful).

One of the challenges in modern software business is getting a sensible test data. This is especially important for performance testing where data needs to be generated in order to saturate the system to ensure it works well under normal conditions.

One of the techniques we like is to use Faker.js. This is a Node/Javascript package which simplifies creating meaningful names and content. Code for this post is on our Github repo.

The essential part of the code is below. It consist effectively of four parts: open connection to Postgresql, create table, generate data and perform insert. Final names actually look pretty good.

    // create client
    const client = new PG.Client({ connectionString: process.env.DB_CONNECTION_STRING })
// connect
await client.connect()

// create table
await client.query(sql)

// generate data
const arr = _.range(numRecords).map(i => {
    const rc = faker.helpers.createCard()
    return {
        name: rc.company.name,
        business: rc.company.bs,
        phone: rc.phone,
        address: rc.address.streetA + ', ' + rc.address.streetB + ', ' + rc.address.zipcode + ' ' + rc.address.city + ', ' + rc.address.county
    }
}).map(x => [x.name, x.business, x.phone, x.address])

// perform insert
const insertSql = format('insert into counterparties( name, business, phone, address) values %L returning id', arr)
const res = await client.query(insertSql)

Final table

Photo by Sergey Semin on Unsplash