Skip to main content

Blog #26: Everything I Know About Playwright Syntax in One Post (So Far!)

Whether you're just starting your automation journey or transitioning from manual testing, Playwright is a powerful framework for modern end-to-end testing. In this blog, I’ll walk you through Playwright syntax in detail, including locators, assertions, waits, and more—all in one place.

✅ 1. Installation & Setup

npm init -y
npm install -D @playwright/test
npx playwright install

This sets up everything you need, including Chromium, Firefox, and WebKit.

🧪 2. Basic Test Structure

import { test, expect } from '@playwright/test';

test('basic test', async ({ page }) => {
  await page.goto('https://www.google.com/');
  const title = await page.title();
  expect(title).toBe('Google');
});
  • test() defines a test case.
  • expect() is used for assertions.

🔍 3. All About Locators

🎯 Playwright-Specific Locators

page.getByText('Login');  // matches visible text
page.getByRole('button', { name: 'Submit' }); // ARIA role
page.getByLabel('Email'); // form label
page.getByPlaceholder('Enter your name'); 
page.getByTestId('login-button'); // using data-testid

🎨 CSS Selectors

page.locator('#username');            // ID
page.locator('.btn.primary');         // Class
page.locator('input[name="email"]');  // Attribute
page.locator('div > span');           // Child
page.locator('ul li:nth-child(2)');   // nth-child
page.locator('form:has(button)');
page.locator('li:has-text("Product")');

⏱️ 4. Waits in Playwright

Playwright auto-waits for actions and assertions, but sometimes you need manual waits.

🔄 Auto-Waiting

Playwright auto-waits for elements to be:

  • Attached to the DOM
  • Visible
  • Stable

⏰ Manual Waits

await page.waitForSelector('#loading-done');
await page.waitForTimeout(3000);// hard wait (use sparingly)
await page.waitForLoadState('domcontentloaded');// 'load', 'networkidle'

📑 Wait for Navigation

await Promise.all([
  page.waitForNavigation(),
  page.click('a[href="/dashboard"]'),
]);

📌5. Page Actions

await page.click('text=Login');
await page.fill('#email', 'user@example.com');
await page.press('#input', 'Enter');
await page.selectOption('select#dropdown', 'value1');
await page.check('#terms');
await page.uncheck('#terms');
await page.hover('button#menu');
await page.setInputFiles('input[type="file"]', 'image.png');

🧪 6. Assertions with expect()

✅ Text & Visibility

await expect(page.locator('h1')).toHaveText('Welcome');
await expect(page.locator('button')).toBeVisible();
await expect(page.locator('input')).toBeHidden();

✅ Attributes

await expect(page.locator('input')).toHaveAttribute('type', 'email');
await expect(page.locator('img')).toHaveAttribute('src', /logo/);

✅ State

await expect(page.locator('input')).toBeEnabled();
await expect(page.locator('input')).toBeEditable();
await expect(page.locator('input')).toBeChecked(); // for checkboxes/radios

✅ URL and Title

await expect(page).toHaveURL(/.*dashboard/);
await expect(page).toHaveTitle('Dashboard');

✅ Count

await expect(page.locator('li')).toHaveCount(5);

🧭 7. Navigation

await page.goto('https://google.com');
await page.goBack();
await page.goForward();
await page.reload();

🧱 8. Browser, Context, Page

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch({ headless: false });
  const context = await browser.newContext();
  const page = await context.newPage();

  await page.goto('https://example.com');
  await browser.close();
})();

🧼 9. Test Hooks

test.beforeEach(async ({ page }) => {
  await page.goto('https://example.com');
});

test.afterEach(async ({ page }) => {
  await page.close();
});

📹 10. Screenshots, Videos & Tracing

📸 Screenshot

await page.screenshot({ path: 'page.png' });

📹 Config (playwright.config.js)

use: {
  screenshot: 'only-on-failure',
  video: 'retain-on-failure',
  trace: 'retain-on-failure',
}

🧪 11. Run Tests

npx playwright test
npx playwright test login.spec.js
npx playwright test --headed
npx playwright show-report

🔄 12. Parallel Testing with Projects

projects: [
  {
    name: 'chromium',
    use: { browserName: 'chromium' },
  },
  {
    name: 'firefox',
    use: { browserName: 'firefox' },
  },
],


🎯 Final Thoughts

When I started learning Playwright, the syntax felt overwhelming. But with consistent practice, breaking things down step by step, and writing small tests every day, it began to make sense. This blog is a reflection of everything I’ve explored so far—from basic actions to assertions, waits, and useful configurations.

If you’re also starting out, I hope this post becomes your go-to reference whenever you feel stuck or need a quick syntax refresher. Don’t worry about learning everything at once—just focus on one part at a time and keep experimenting.

Playwright is more than just a tool; it’s a great way to build confidence in automation. I’ll keep sharing as I learn more—and I’d love to hear what helped you or what you’re exploring next!

Happy testing! 🎉



Comments

Popular posts from this blog

Blog # 9: Say Hello to Alerts! Handling Dialog Boxes in Playwright

Alerts and dialogs are common elements in web applications that can interrupt automated test flows if not handled properly. Playwright provides straightforward methods to manage these interruptions, ensuring your tests run smoothly. In this guide, I’ll share how I learned handling three types of dialogs—simple alerts, confirmation boxes, and prompts—using Playwright’s built-in features. Why Handle Dialogs? Dialogs often appear during critical user interactions, such as form submissions, error notifications, or data input requests. If ignored, they can cause tests to freeze or fail. Playwright’s dialog-handling capabilities allow you to: Validate dialog messages. Accept, dismiss, or respond to prompts programmatically. Keep tests resilient and predictable. Let’s explore how to tackle each type of dialog. 1.  Simple Alerts: The One-Way Notification A simple alert is a basic pop-up with an "OK" button. Example Scenario : A basic alert appears, shouting, "I am an alert box!...

Blog # 20 :🎪 Playwright Hooks: Your Test Suite’s Best Friends!

🎩 Why Hooks? The Magic Behind the Scenes When writing automated tests, especially for web applications, repetitive tasks like logging in before each test or cleaning up after the test run can quickly clutter your code. If you've found yourself copying the same setup code into multiple tests, you're not alone! Luckily, Playwright offers a powerful feature to solve this — hooks . Imagine you’re hosting a party 🥳. You wouldn’t clean the house after every guest leaves, right? Instead, you’d: 🏗️  Setup once (decorate, cook food) → beforeAll 🗑️ Clean as you go (refill snacks, wipe spills) → beforeEach/afterEach 💣Nuclear cleanup after everyone leaves → afterAll In testing terms: Hooks automate repetitive tasks so your tests can focus on what matters. 🔮 Meet the 4 Hooks 🚀 Your Code in Action: Login/Logout Flow Let’s automate a shopping site test (your code!). Step 1: beforeEach – The “Welcome Mat” Why it rocks: Every test starts fresh, logged in, and cookie-free! test. beforeEa...

Software Testing Heuristics and mnemonics.

Software Testing Heuristics Heuristics are simply experience-based techniques for problem-solving, learning, and discovery. Where an exhaustive search is impractical, heuristic methods are used to speed up the process of finding a satisfactory solution. Examples of this method include using a rule of thumb, an educated guess, an intuitive judgment, or common sense. When you face a problem, you try some solutions that may work. For instance, if you suddenly find your mobile hang, what do you do? You may restart your mobile first. If that doesn’t work, then you may check & update the latest software and uninstall suspicious apps.if that also doesn’t work, then you reset your phone setting ( Factory reset). Most of us try a number of steps to solve our problems. These steps may not always work but we try them because we know that they may work. Following heuristics can apply to absolutely any kind of system with any kind of interface.  1.Abstract  Remove details in a model. S...

Blog # 4 : A Deep Dive into Playwright Assertions

  Ever spent hours debugging a test only to realize you forgot to check if a button was actually clickable? In web testing, the devil's in the details—and that's where assertions become your best friend. Let's explore how Playwright's assertion library can transform your testing strategy, using the popular The Internet testing playground. Why Assertions Matter Assertions are the backbone of any meaningful test. They're the checkpoints that scream, "This works!" or "Something's broken here!" Playwright's built-in expect library shines when testing real-world scenarios like authentication flows and dynamic content. Let's Start Testing: A Real-World Scenario We'll be testing key features of The Internet playground. Here's our foundation: Now let's add powerful assertions. Validating Content: Is What You See What You Get? 1. Page Titles: Your First Line of Defense Verify you're on the correct page immediately after na...

Day 15 Name five different online payment methods.

Most modern online payment services offer easy-to-use, fast and secure ways to pay Here’s a list of some of the most popular online payment services: Digital Wallet ( E wallet) A digital wallet refers to software, an electronic device, or an online service that enables individuals or businesses to make transactions electronically. It stores the payment information of users for different payment modes on various websites.                           PayPal PayPal is one of the most dominant payment methods available today. over 20 million UK shoppers use PayPal each year in the UK and  7 million businesses worldwide use their platform to accept payments. PayPal is an eCommerce payment processing company that allows users to set up a PayPal account and pay a fee for each cash transaction. Many customers prefer to checkout with PayPal because it’s so simple and quick to use. Amazon Pay Amazon Pay is another ...

Blog # 16: Diving into Screenshots with Playwright — Let’s Get Snapping! 🚀

Hi everyone! 👋  I’ve been exploring more of what Playwright has to offer, and I recently discovered an exciting feature—screenshots! Whether you're validating UI elements, documenting test results, or just sprinkling some eye candy into your reports 😄, screenshots can truly elevate your testing game. Let me share my recent adventures in capturing various types of screenshots using Playwright! Here’s what I tried out: A quick snapshot of the web page 🖼️ A comprehensive full-page capture, scroll and all! 📜 A focused screenshot of a specific element — like that one product image you love! 🔍 Let’s dive in! ✨ 1. Quick Page Screenshot const { test, expect } = require ( '@playwright/test' ); test ( 'Save a dated screenshot for future-you' , async ({ page }) => { await page. goto ( 'https://www.demoblaze.com/' ); // Pro move: Use ISO date (no messy slashes!) const today = new Date (). toISOString (). split ( 'T' )[0]; // "2023-09...

✍️ Blog #23: What I Learned About Annotations in Playwright

When I started, I thought writing tests was just about getting them to pass. But as the number of tests grew, I realized that being able to control which ones run, which to skip, and how to debug easily — is just as important. Let me take you through everything I’ve learned so far about Playwright’s annotations. 🔍 What Are Annotations? Annotations are special helpers in Playwright that let you modify test behavior without changing the actual logic of the test. They're great for: Focusing on a single test ( test.only ) Skipping unfinished or flaky ones ( test.skip ) Flagging tests that need fixing  ( test.fixme ) Allowing known failures  ( test.fail ) Marking slow tests  ( test.slow ) Think of them like post-it notes or switches you can stick on your tests to manage them better during testing. ✅ Test-Level Annotations These annotations go directly on individual tests. 🧪 test.only – Focus on One Test test. only ( 'run this test only' , async ...