Generation of random data for tests using the same object

139 Views Asked by At

I have a normal object in which I use a faker to generate random values:

const product = {
            id: faker.random.numeric(6),
            note: faker.random.word(),
        };

I have two tests that have a step that takes this object as an argument

test('Populate form', async ({
  dashboardPage,
  page,
}) => {
  await dashboardPage.createNewProduct(product);
  await expect(page).toHaveScreenshot();
});

The problem is that the data generated in this object during the run of these tests is random only for one test, while for the second it will be the same as for the first. What is the problem and how can it be solved?

I tried to generate this object using a synchronous function, but that didn't help either

function generateNewData() {
           return {
            id: faker.random.numeric(6),
            note: faker.random.word(),
           }
       };
test('Populate form', async ({
  dashboardPage,
  page,
}) => {
  const product = generateNewData();
  await dashboardPage.createNewProduct(product);
  await expect(page).toHaveScreenshot();
});
2

There are 2 best solutions below

0
BernardV On

Perhaps something like the below could work. If it does not work perhaps your faker initialization is not working correctly.

var newRandomProductOne = createNewRandomProduct(faker.random.numeric(6), faker.random.word());
var newRandomProductTwo = createNewRandomProduct(faker.random.numeric(6), faker.random.word());

function createNewRandomProduct(id, note) {  
  return {
    id: id,
    note: note
  };
}
0
candre On

Using an async function seem to work, generating unique data for each test:

async function generateProduct() {
    return {
        id: faker.random.numeric(6),
        note: faker.random.word(),
    }
}

// Running test parameterized and calling function twice in each run:
for(const scenario of ['1', '2']) {
    test(`Populate form ${scenario}`, async ({ page }) => {
        console.log(await generateProduct())
        console.log(await generateProduct())
    });
}

Results in:

  ✓  1 [chrome web] › product.spec.ts:17:9 › Populate form 1 (148ms)
{ id: '964561', note: 'West' }
{ id: '836858', note: 'person' }
  ✓  2 [chrome web] › product.spec.ts:17:9 › Populate form 2 (46ms)
{ id: '294908', note: 'Gasoline' }
{ id: '890586', note: 'Smykker' }