I create tests in Playwright. I generate random registration data in fixture.
fixtures.ts:
import { test as baseTest } from '@playwright/test';
import constants from './constans.json';
const randomFigures = Math.random().toString();
const randomSuffix = randomFigures.substr(10);
constants.randomEmail = randomFigures.substr(2) + '@email.com';
constants.randomPhone = randomFigures.substr(2, 6);
type pageData = {
constants: typeof constants;
};
const fixture = baseTest.extend<pageData>({ constants });
export const test = fixture;
constans.js:
{
"password": "password",
"randomEmail": "",
"randomPhone": "",
}
I use this random data in my tests:
const { expect } = require('@playwright/test');
import { test } from './fixtures';
test.beforeEach(async ({ page }) => {
await page.goto(`https://xyx.com`);
});
test('test1', async ({ page, constants }) => {
await page.locator('[data-e2e="register"]').click();
await page.locator('[data-e2e="email"]').fill(constants.randomEmail);
await page.locator('[data-e2e="phone"]').fill(constants.randomPhone);
await page.locator('[data-e2e="password"]"]').fill(constants.password);
await page.locator('[data-e2e="button-register"]').click();
});
test('test2', async ({ page, constants }) => {
await page.locator('[data-e2e="register"]').click();
await page.locator('[data-e2e="email"]').fill(constants.randomEmail);
await page.locator('[data-e2e="phone"]').fill(constants.randomPhone);
await page.locator('[data-e2e="password"]').fill(constants.password);
await page.locator('[data-e2e="button-register"]').click();
});
What's the problem?
The problem is that test1 gets pass and test2 gets failed when I run both of these tests. This problem is because test1 and test2 get the same registration data, which causes test2 to get an error that an account with this data already exists.
What I tried to solve?
I've tried various other ways to declare and use fixtures. I also tried to declare and return constants inside fixtures. But each time the problem persisted.
Your fixture is compiled and generated at runtime, meaning that your variables randomFigures
and randomSuffix
are constant for the duration of the tests, which is why you're running into the issues you're currently seeing. Instead, try writing a helper function which you can call to generate your random constants for you. It might look something like this:
export const randomEmail = () => {
return Math.random().toString().substr(2) + '@email.com';
}
export const randomPhone = () => {
return Math.random().toString().substr(2, 6);
}