Situation

My task was to create random test data for an application, which didn’t have an API for data creation. I simply chose to write e2e tests with Playwright and I only had to figure out how to select random values.

Solution

After googling, looking on Stackoverflow and asking ChatGPT - I managed to write the following code.

import { test } from '@playwright/test'

test('select random option', async ({ page }) => {
    // you can also use any other locator
    const select = page.locator('#id_of_the_select')
    const options = select.locator('option')

    // sometimes you want to exclude the first option, change it to 1
    const min = 0
    const max = (await options.count()) - 1
    const index = Math.floor(min + Math.random() * (max - min + 1))

    await select.selectOption({ index: index })
})