Sometimes when you’re writing a test you’ll find you want to run the same test multiple times, but with different data.
For example let’s say you need tests for a UK e-commerce website to verify that the correct sales tax (VAT) is applied to purchases. Most products in the UK incur VAT of 20% but there are exceptions:
- Books = 0%
- Children’s clothing = 0%
- Toys = 0%
- Solar panels = 5%
These could be written as 4 separate tests but since the steps will be identical it’s easier and more maintainable to write as a single, parameterized Playwright automated test.
To do this create an array of the data parameters, and then write a looping mechanism enveloping the test, iterating through each of the data sets.
// define your Playwright test data in an array of parameters
const productData = [
{ name: 'knowledge of angels book', tax: '0' },
{ name: 'Nike Boys T-Shirt', tax: '0' },
{ name: 'LEGO Triceratops', tax: '0' },
{ name: 'Jackery Solar 100W', tax: '5' },
]
for (const product of productData) {
test(`Sales tax test for ${product.name}`, async ({page}) => {
await page.goto('https://www.example.com');
// locate product
await page.locator('#searchField').fill(product.name);
await page.locator('#searchButton').click();
// add to basket
await page.locator('#product1').click();
await page.locator('#addToBasket').click();
// verify correct sales tax applied
await page.locator('#goToBasket').click();
await expect(page.locator('#tax1')).toHaveText(product.tax);
});
}
When you execute this you will see Playwright running 4 tests.
Also note the execution log will show a different test name for each test because we added the product name in the test description:
test(`Sales tax test for ${product.name}`, async ({page}) => {
I hope this simple guide to parameterizing Playwright tests has been useful!