Tutorial 10 – Parameterize a test in Playwright
What you will Learn in this blog:
Parameterize a Test
Locate an element using text (Text locator)
Code snippet
Parameterize a Test in PW
Sometimes we may want to execute a Test with multiple sets of data. As an example, let us launch
http://zero.webappsecurity.com/login.html
We have a ‘Login’ field here. We may want to login with different user ids for different tests. It does not make sense to automate the same login functionality again and again for different user ids (since the code logic would be same).
So instead, what we do is that, we write a piece of code for login functionality and then parametrize it for different user ids.
Before we practically see this, let us first inspect the above ‘Login’ field
Make a note of ‘id’, we would be using it in our script to locate this field.
Now, to begin with, we will first create a constant holding the 3 test user names
We will than use the ‘for’ loop that will iterate over these usernames (the ‘name’ variable in the ‘for’ loop will hold the different user ids at runtime)
Now, launch https://playwright.dev/docs/test-parameterize
Copy the below syntax, make a special note of the backtick
Create a test and use the above syntax
Next, in line#11, we are picking a username from the ‘name’ variable at runtime and typing the same in the ‘Login’ field
Cut the ‘test’ block and paste it inside the ‘for’ loop
So the comple code looks like below
Let us save and execute, notice below that the test gets executed 3 times (for each of the 3 user ids)
See the output below
So this is how we can easily parametrize our tests in playwright.
Locate an element using text (Text locator)
Launch https://the-internet.herokuapp.com/
Let us suppose we want to click any link ‘A/B Testing’
We can simply use the text of the above link and use it in our script.
The below page comes up when we click the above link
We have already seen the ‘locator’ method
Below, we are using the (“text=<text of the link>”).click operation to click the element
Save an run the script, notice below that the link gets clicked and the new page opens
Let us try another link
Save and run
Notice below that the link gets clicked and the new page opens
So this is how we use the text locator to click any link based upon its text.
Code snippet
import {test,expect} from '@playwright/test'
const people = ['TestUser1', 'TestUser2', 'TestUser3']
for (const name of people) {
test(`testing with ${name}`, async ({ page }) => {
await page.goto('http://zero.webappsecurity.com/login.html')
await page.type('#user_login', `${name}`)
await page.waitForTimeout(4000)
})
}
test.only("using text locator to click element", async ({ page }) => {
await page.goto('https://the-internet.herokuapp.com/')
//await page.locator("text=A/B Testing").click()
await page.locator("text=Context Menu").click()
await page.pause()
})
Thank you for reading!