Playwright Locators and Assertions Explained with Examples | Day 3 | Playwright with JavaScript in 30 Days Challenge | Tech Bharat
📘 Locators in Playwright
🔑 Two Important Points in Automation
Locate the element
Perform an action on the element
🧩 Common Web Elements
- Radio buttons
- Input fields
- Checkboxes
- Images
- Dropdowns
- Links
- Etc.
🔍 Ways to Locate Elements
We can locate elements by using, such as:
- unique properties from the DOM
- CSS Selectors
- XPath
📦 Importing Playwright Modules
There are two ways to import modules:
// Method 1 (CommonJS)
const { test, expect } = require('@playwright/test');
// Method 2 (ES Modules)
import { test, expect } from '@playwright/test';
const {test,expect}=require('@playwright/test'); // this is first way to import
// import {test,expect} from '@playwright/test' //this is another way to import the test and expect from @playwright/test
✅ Note: Semicolons are optional in JavaScript.
🎯 Locating and Performing Actions
Method 1: Using locator()
await page.locator("selector").click(); : first locate the element and then click the element
Method 2: Direct action
await page.click("selector"); : perform the click action on the element whichever is having this particular locator
🖱️ Common Actions
- click() → Click an element
- fill() → Enter text into an input field
- type() → Another way to enter text
- count() → Count the webelement
- toBeVisible() → check whether the element is visible or not, used for assertion
- textContent() → It will extract the text content from a webelement
🧪 Example: Using Properties
// Using locator
await page.locator("id=login2").click();
// Direct method
await page.click("id=login2");
🎨 CSS Selectors
- ID selector starts with #
- Class selector starts with a dot (.)
// Using CSS selector
await page.locator("#loginusername").fill("pavanol");
// Alternative
await page.fill("#loginusername", "pavanol");
🧭 XPath Example
await page.click("//button[normalize-space()='Log in']");
👀 Visibility Assertion
toBeVisible(): This is used to check whether the element is visible or not on the web.
const logout = page.locator("id=logout2");
await expect(logout).toBeVisible();
const logoutButton = page.locator('#logout2');
await expect(logoutButton).toBeVisible();
📊 Handling Multiple Elements
Using $$ (returns an array)
const elements = await page.$$("a"); // returns array
const allLinks=await page.$$('a')
- If no elements are found → returns []
Recommended: Using locator()
const allLinks = page.locator("a");
// 🔗 Print All Links
// ======================
const allLinks = page.locator('a');
⏳ Wait for Element
await page.waitForSelector("div[id='tbodyid'] h4 a");
await page.waitForSelector("div[id='tbodyid'] h4 a")
Waits until the element is visible in the DOM.
Another way : await products.first().waitFor(); // Ensure products are loaded
await products.first().waitFor(); // ensures products are loaded
📝 textContent()
textContent(): this is used to get the content from a locator
// 🔗 Print All Links
// ======================
const allLinks = page.locator('a');
const linkCount = await allLinks.count();
console.log(`Total links: ${linkCount}`);
for (let i = 0; i < linkCount; i++) {
const text = await allLinks.nth(i).textContent();
console.log(text);
}
👁️ Visibility Check
const isVisible = await page.locator("selector").isVisible();
- Returns true if visible, otherwise false
🔢 Count Elements
const count = await page.locator("selector").count();
✅ Assertions in Playwright
🚀 Complete Example Test Case
const { test, expect } = require('@playwright/test');
test('Login and validate products', async ({ page }) => {
// ======================
// 🌐 Navigate to website
// ======================
await page.goto('https://demoblaze.com');
// ======================
// 🔐 Perform Login
// ======================
await page.locator('#login2').click();
await page.locator('#loginusername').fill('pavanol');
await page.locator('#loginpassword').fill('test@123');
await page.locator("//button[normalize-space()='Log in']").click();
// ======================
// ✅ Verify Login Success
// ======================
const logoutButton = page.locator('#logout2');
await expect(logoutButton).toBeVisible();
console.log('Login successful:', await logoutButton.isVisible());
// ======================
// 🔗 Print All Links
// ======================
const allLinks = page.locator('a');
const linkCount = await allLinks.count();
console.log(`Total links: ${linkCount}`);
for (let i = 0; i < linkCount; i++) {
const text = await allLinks.nth(i).textContent();
console.log(text);
}
// ======================
// 🛍️ Print Product Names
// ======================
const products = page.locator("div#tbodyid h4 a");
await products.first().waitFor(); // ensures products are loaded
const productCount = await products.count();
console.log(`Total products: ${productCount}`);
for (let i = 0; i < productCount; i++) {
const productName = await products.nth(i).textContent();
console.log(productName);
}
});
Built-in Locators in Playwright
Playwright provides several built-in locators to identify web elements easily and reliably.
1. page.getByRole()
Used to locate elements by their explicit or implicit accessibility roles.
// Locate a button using its role
await page.getByRole('button', { name: 'Submit' }).click();
2. page.getByText()
Used to locate elements based on their text content.
// Locate an element using visible text
await page.getByText('Login').click();
Use this locator when the element contains visible text.
3. page.getByLabel()
Used to locate form controls using the associated label text.
Example HTML
<label>Password <input type="password" /></label>
Playwright Code
// Locate input using label text
await page.getByLabel('Password').fill('secret');
This is commonly used for input fields connected with labels.
4. page.getByPlaceholder()
Used to locate input fields using the placeholder attribute.
You can use this locator only when the element contains a placeholder attribute.
// Locate input fields using placeholder text
await page.getByPlaceholder('Username').fill('Admin'); // Enter username
await page.getByPlaceholder('Password').fill('Admin'); // Enter password
5. page.getByAltText()
Used to locate elements (usually images) using the alt attribute.
Mostly used for image elements.
You can use this locator only when the element contains an alt attribute.
// Locate image using alt text
const companyLogo = page.getByAltText('company-branding');
// Validate visibility
await expect(companyLogo).toBeVisible();
6. page.getByTitle()
Used to locate elements using the title attribute.
Example HTML
<span title="Issues count">25 issues</span>
Playwright Code
// Validate text using title attribute
await expect(page.getByTitle('Issues count'))
.toHaveText('25 issues');
7. page.getByTestId()
Used to locate elements using the data-testid attribute.
Example HTML
<button data-testid="directions">Itinéraire</button>
Playwright Code
// Locate element using test id
await page.getByTestId('directions').click();
getByTestId() is very useful in automation because test IDs are stable and less likely to change.
Complete code
import{test, expect} from '@playwright/test';
test("study bulit in locator",async ({page})=>{
await page.goto("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");
//page.getByAltText() to locate an element, usually image, by its text alternative. : check the alt attribute from DOM. like for a image tag, alt tag is present
const comanyLogo=await page.getByAltText("company-branding");
await expect(comanyLogo).toBeVisible();
//page.getByPlaceholder() to locate an input by placeholder.
await page.getByPlaceholder("Username").fill("Admin"); //enter user name
await page.getByPlaceholder("Password").fill("admin123"); //enter password
// page.getByRole() to locate by explicit and implicit accessibility attributes.
await page.getByRole("button",{type: "submit"}).click();
//page.getByText() to locate by text content. We can use it which is having text content.
const userNameLocator=await page.locator(".oxd-userdropdown-name");
await userNameLocator.first().waitFor();
const userName= await page.locator(".oxd-userdropdown-name").textContent();
console.log("this is name"+ userName);
await expect(await page.getByText(userName)).toBeVisible();
})
- Join our Telegram channel: https://t.me/thetechbharat
- Join our WhatsApp Group: https://chat.whatsapp.com/BBu2ZXxqASr7AHilRfSUzh?mode=gi_t
- Follow us for more info: www.linkedin.com/in/rajat-bhatti
- Subscribe to our YouTube channel: https://www.youtube.com/@Techbharat12


Post a Comment