Introduction
If you are starting with Playwright automation testing, learning the Playwright basic commands is the best place to begin. These commands help QA engineers open browsers, navigate web pages, locate elements, perform actions, validate results, capture screenshots, debug failures, and execute automated tests.
Playwright is a modern end-to-end testing framework that supports Chromium, Firefox, and WebKit. With Playwright Test, you also get fixtures, assertions, parallel execution, reporting, tracing, and browser configuration.
For Selenium engineers, many concepts will look familiar. However, Playwright provides built-in auto-waiting and modern locators that can make tests more reliable when used correctly. Playwright recommends user-facing locators such as getByRole() for resilient tests.
This Playwright basic commands tutorial explains the commands you need to know as a beginner, with practical Playwright TypeScript examples.
What Are Playwright Basic Commands?
Playwright basic commands are API methods and CLI commands used to control browsers and execute automated tests.
Common categories include:
| Category | Important Commands |
| Browser | chromium.launch(), browser.close() |
| Page | newPage(), page.url() |
| Navigation | goto(), reload(), goBack(), goForward() |
| Locators | getByRole(), getByText(), getByLabel(), locator() |
| Actions | click(), fill(), check(), uncheck() |
| Dropdowns | selectOption() |
| Keyboard | press() |
| Mouse | hover() |
| Assertions | expect() |
| Synchronization | waitForURL(), waitForLoadState() |
| Evidence | screenshot() |
| CLI | npx playwright test, –headed, –debug |
| Reporting | npx playwright show-report |
Learning these Playwright commands for beginners gives you a foundation for building maintainable automation frameworks.
Playwright Installation and Project Setup
Step 1: Install Node.js
Playwright with TypeScript requires Node.js. After installing Node.js, verify it:
node –version
npm –version
Step 2: Create a Playwright project
mkdir playwright-basic-commands
cd playwright-basic-commands
npm init playwright@latest
Choose TypeScript when the installer asks for the language.
Install the required browsers with:
Playwright’s CLI supports installing all browsers or individual browsers such as Chromium, Firefox, or WebKit.
A typical project contains:
playwright-basic-commands/
├── tests/
│ └── example.spec.ts
├── playwright.config.ts
├── package.json
└── tsconfig.json
Playwright Command Categories and Syntax
Most Playwright TypeScript commands follow this pattern:
await page.command();
For example:
await page.goto(‘https://example.com’);
Because browser operations are asynchronous, Playwright commands generally use await.
A typical test looks like:
import { test, expect } from ‘@playwright/test’;
test(‘basic Playwright test‘, async ({ page }) => {
await page.goto(‘https://example.com’);
await expect(page).toHaveTitle(/Example/);
});
The page fixture represents a browser tab and provides navigation and interaction APIs. A BrowserContext can contain multiple pages.
Browser and Page Commands
1. Launch a Browser
Command → chromium.launch()
Syntax:
const browser = await chromium.launch();
Example:
import { chromium } from ‘@playwright/test’;
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();
Explanation: Launches Chromium and creates a browser context and page.
Expected Result: A browser opens and navigates to the specified website.
Best Practice: In normal Playwright Test projects, prefer the built-in page fixture rather than manually launching browsers for every test.
2. Create a New Page
Command → context.newPage()
const context = await browser.newContext();
const page = await context.newPage();
A page represents a browser tab or popup.
3. Close the Browser
await browser.close();
Use this when manually controlling the browser. Playwright Test normally manages browser lifecycle for you.
Playwright Navigation Commands
Navigation is one of the most important groups of Playwright automation commands.
page.goto()
Syntax:
await page.goto(‘URL’);
Example:
await page.goto(‘https://example.com’);
Explanation: Navigates the current page to a URL.
Expected Result: The requested website opens.
Best Practice: Use baseURL in playwright.config.ts for large projects so tests can use paths instead of repeating full URLs.
page.reload()
await page.reload();
Reloads the current page.
Use it when testing refresh behavior or verifying whether application state survives a reload.
page.goBack()
await page.goBack();
Moves to the previous browser history entry.
page.goForward()
await page.goForward();
Moves to the next browser history entry.
Navigation Example
import { test, expect } from ‘@playwright/test’;
test(‘navigation commands’, async ({ page }) => {
await page.goto(‘https://example.com’);
await page.reload();
await page.goBack();
await page.goForward();
await expect(page).toHaveURL(/example/);
});
Playwright Locator Commands
Locators are central to Playwright testing.
getByRole()
Syntax:
page.getByRole(‘button’, { name: ‘Login’ })
Example:
await page.getByRole(‘button’, { name: ‘Login’ }).click();
Explanation: Finds an element based on its accessible role and name.
Best Practice: Prefer role-based locators where appropriate because they closely represent how users interact with the application.
getByText()
await page.getByText(‘Welcome to our store’).click();
Use it when visible text provides a reliable identifier.
getByLabel()
await page.getByLabel(‘Email’).fill(‘tester@example.com’);
This is especially useful for form fields associated with labels.
locator()
await page.locator(‘#username’).fill(‘admin’);
You can also use CSS:
await page.locator(‘.login-button’).click();
Best Practice: Do not automatically use CSS selectors for everything. Prefer semantic locators such as getByRole() and getByLabel() when they provide a stable target.
Element Interaction Commands
click()
await page.getByRole(‘button’, { name: ‘Submit’ }).click();
Clicks an element.
fill()
await page.getByLabel(‘Username’).fill(‘admin’);
Clears the existing value and enters new text.
check() and uncheck()
await page.getByLabel(‘Remember me’).check();
await page.getByLabel(‘Remember me’).uncheck();
Use these for checkboxes.
selectOption()
await page.getByLabel(‘Country’).selectOption(‘India’);
For a <select> element, selectOption() selects the required value.
Keyboard and Mouse Commands
press()
await page.getByLabel(‘Search’).press(‘Enter’);
You can also press combinations:
await page.keyboard.press(‘Control+A’);
await page.keyboard.press(‘Backspace’);
hover()
await page.getByRole(‘button’, { name: ‘Products’ }).hover();
Useful for menus, tooltips, and hover-based interactions.
Example:
await page.getByText(‘Products’).hover();
await page.getByText(‘Laptops’).click();
Assertions Using expect()
Assertions verify expected application behavior.
import { test, expect } from ‘@playwright/test’;
test(‘verify page’, async ({ page }) => {
await page.goto(‘https://example.com’);
await expect(page).toHaveTitle(/Example/);
await expect(page.getByRole(‘heading’)).toBeVisible();
});
Common assertions include:
await expect(locator).toBeVisible();
await expect(locator).toBeEnabled();
await expect(locator).toHaveText(‘Welcome’);
await expect(locator).toHaveValue(‘admin’);
await expect(page).toHaveURL(/dashboard/);
await expect(page).toHaveTitle(/Dashboard/);
Best Practice: Prefer web-first assertions over manually retrieving values and using ordinary JavaScript assertions. They can wait for the expected condition.
Auto-Waiting and Timeout Commands
One major Playwright advantage is automatic waiting.
For example:
await page.getByRole(‘button’, { name: ‘Submit’ }).click();
Playwright waits for the locator to become actionable instead of requiring you to insert a fixed delay.
Avoid:
await page.waitForTimeout(5000);
A fixed sleep can make tests slow and flaky.
Instead, use meaningful synchronization.
waitForURL()
await page.getByRole(‘button’, { name: ‘Login’ }).click();
await page.waitForURL(‘**/dashboard’);
Use it when an action causes navigation.
waitForLoadState()
await page.waitForLoadState(‘networkidle’);
Use load-state waiting only when it actually matches the application’s behavior. Locator assertions are often a better synchronization mechanism.
Example:
await page.goto(‘https://example.com’);
await expect(page.getByRole(‘heading’)).toBeVisible();
Playwright configuration also allows separate test and assertion timeouts.
Handling Common UI Scenarios
Dropdowns
await page.getByLabel(‘Department’).selectOption(‘qa’);
Checkboxes
await page.getByLabel(‘Accept terms’).check();
Forms
await page.getByLabel(‘Name’).fill(‘John’);
await page.getByLabel(‘Email’).fill(‘john@example.com’);
await page.getByRole(‘button’, { name: ‘Submit’ }).click();
Alerts
For browser dialogs:
page.on(‘dialog’, async dialog => {
console.log(dialog.message());
await dialog.accept();
});
Frames
const frame = page.frameLocator(‘#payment-frame’);
await frame.getByLabel(‘Card Number’).fill(‘4111111111111111’);
Popups and Multiple Pages
const popupPromise = page.waitForEvent(‘popup’);
await page.getByText(‘Open account’).click();
const popup = await popupPromise;
await popup.waitForLoadState();
console.log(await popup.title());
A BrowserContext can contain multiple pages, making it possible to test popup and multi-tab workflows.
Screenshot, Video, Trace, and Reporting Commands
screenshot()
Syntax:
await page.screenshot({ path: ‘homepage.png’ });
Example:
await page.goto(‘https://example.com’);
await page.screenshot({
path: ‘screenshots/homepage.png’,
fullPage: true
});
Use screenshots for visual evidence and debugging.
Playwright Test can also automatically capture screenshots, videos, and traces through configuration.
Example:
export default defineConfig({
use: {
screenshot: ‘only-on-failure’,
video: ‘on-first-retry’,
trace: ‘on-first-retry’
}
});
Trace Viewer is especially useful for investigating failed automation because it provides detailed execution information.
Open the report with:
npx playwright show-report
Browser Context and Test Configuration
A context provides an isolated browser environment.
const context = await browser.newContext({
viewport: { width: 1280, height: 720 }
});
const page = await context.newPage();
In a real framework, configure common settings centrally:
import { defineConfig } from ‘@playwright/test’;
export default defineConfig({
testDir: ‘./tests’,
use: {
baseURL: ‘https://example.com’,
screenshot: ‘only-on-failure’,
trace: ‘on-first-retry’,
video: ‘on-first-retry’
}
});
This reduces duplicated setup and makes the framework easier to maintain.
Playwright Test Runner Commands
Important Playwright test runner commands include:
npx playwright test
Run all tests.
npx playwright test tests/login.spec.ts
Run one test file.
npx playwright test –headed
Run with a visible browser.
npx playwright test –debug
Open Playwright Inspector for debugging.
npx playwright test –ui
Run UI Mode.
npx playwright test –project=chromium
Run a specific configured browser project.
npx playwright test -g “login
Run tests matching a title.
npx playwright show-report
Open the HTML report.
These commands are part of the current Playwright CLI and are useful in local development and CI workflows.
Real-World Playwright Command Example: Login Automation
Here is a complete beginner-friendly login example:
import { test, expect } from ‘@playwright/test’;
test(‘successful login’, async ({ page }) => {
await page.goto(‘https://example.com/login’);
await page.getByLabel(‘Username’).fill(‘testuser’);
await page.getByLabel(‘Password’).fill(‘Password123’);
await page.getByRole(‘button’, { name: ‘Login’ }).click();
await page.waitForURL(‘**/dashboard’);
await expect(
page.getByRole(‘heading’, { name: ‘Dashboard’ })
).toBeVisible();
await page.screenshot({
path: ‘screenshots/login-success.png’,
fullPage: true
});
});
A QA engineer can expand this into positive, negative, locked-user, invalid-password, session-timeout, and logout scenarios.
Real-World Example: Form and E-Commerce Testing
import { test, expect } from ‘@playwright/test’;
test(‘product purchase flow’, async ({ page }) => {
await page.goto(‘https://example.com/products’);
await page.getByText(‘Laptop’).click();
await page.getByRole(‘button’, { name: ‘Add to cart’ }).click();
await page.getByRole(‘link’, { name: ‘Cart’ }).click();
await expect(page.getByText(‘Laptop’)).toBeVisible();
await page.getByRole(‘button’, { name: ‘Checkout’ }).click();
await page.getByLabel(‘Full Name’).fill(‘Test User’);
await page.getByLabel(‘Address’).fill(‘Bengaluru’);
await page.getByLabel(‘Country’).selectOption(‘India’);
await page.getByLabel(‘Accept terms’).check();
await page.getByRole(‘button’, { name: ‘Place Order’ }).click();
await expect(page.getByText(‘Order confirmed’)).toBeVisible();
});
This example combines navigation, locators, actions, dropdowns, checkboxes, and assertions.
Common Playwright Command Errors and Solutions
1. Locator not found
Problem:
Timeout exceeded while waiting for locator
Solution: Check the locator and inspect the page with Playwright UI Mode or Inspector.
2. Element is not clickable
The element may be hidden, disabled, covered, or not yet ready.
Prefer a reliable locator and allow Playwright’s actionability checks to work.
3. Wrong locator
Instead of fragile CSS:
page.locator(‘div:nth-child(3) button’)
prefer:
page.getByRole(‘button’, { name: ‘Submit’ })
4. Test passes locally but fails in CI
Enable:
use: {
trace: ‘on-first-retry’,
screenshot: ‘only-on-failure’,
video: ‘on-first-retry’
}
Then inspect the trace and report.
Playwright Basic Command Best Practices
Follow these rules when writing Playwright automation:
- Prefer getByRole() and other user-facing locators.
- Avoid unnecessary waitForTimeout().
- Use expect() for application-state validation.
- Keep selectors stable.
- Use fixtures instead of duplicating browser setup.
- Keep test data separate from test logic.
- Use Page Object Model for larger frameworks.
- Capture traces on retries or failures.
- Run tests across required browser projects.
- Keep tests independent and repeatable.
- Use meaningful test names.
- Run tests in CI before merging code.
These practices help Selenium engineers transition toward modern Playwright automation patterns.
Playwright Interview Questions with Answers
1. What are Playwright basic commands?
They are commonly used Playwright APIs for navigation, locating elements, performing actions, assertions, synchronization, screenshots, browser control, and test execution.
2. What is the difference between locator() and getByRole()?
locator() can use CSS or XPath-style selectors, while getByRole() identifies elements through their accessible role and name. For maintainable tests, user-facing locators are generally preferred.
3. Does Playwright require explicit waits?
Usually no. Playwright automatically waits for many elements to become actionable, and its assertions can wait for expected conditions.
4. How do you run a Playwright test?
npx playwright test
5. How do you debug a Playwright test?
npx playwright test –debug
You can also use:
npx playwright test –ui
6. How do you capture a screenshot?
await page.screenshot({ path: ‘test.png’ });
7. How do you select a dropdown value?
await page.getByLabel(‘Country’).selectOption(‘India’);
Playwright Learning Roadmap for Beginners
If you are learning Playwright for beginners, follow this progression:
Step 1: Learn Playwright installation and project structure.
Step 2: Learn browser, context, and page concepts.
Step 3: Master locators such as getByRole(), getByText(), getByLabel(), and locator().
Step 4: Learn actions such as click, fill, check, select, hover, and keyboard commands.
Step 5: Learn assertions and auto-waiting.
Step 6: Practice forms, dropdowns, alerts, frames, popups, and multiple pages.
Step 7: Learn fixtures and Page Object Model.
Step 8: Add API testing, authentication, data-driven testing, and parallel execution.
Step 9: Learn reporting, tracing, screenshots, and debugging.
Step 10: Integrate Playwright into CI/CD using GitHub Actions, Azure DevOps, or another CI platform.
For career growth, do not stop after memorizing commands. Build a small framework containing login tests, product workflows, reusable page objects, test data, reporting, and CI execution.
Related topics to learn next include Playwright Basics, Playwright for Beginners, Playwright Installation Guide, Playwright First Test Script, Playwright Getting Started Guide, Playwright Simple Example, Playwright TypeScript Tutorial, Playwright Python Tutorial, Playwright Java Tutorial, Playwright Locators, Playwright Auto Waiting, Playwright Page Object Model, Playwright Fixtures Tutorial, Playwright Data Driven Testing Tutorial, Playwright API Testing, Playwright Authentication Tutorial, Playwright Reporting Tutorial, Playwright Parallel Execution Tutorial, Playwright CI/CD Tutorial, Playwright GitHub Actions Tutorial, Playwright Docker Tutorial, Playwright Troubleshooting, and Playwright Interview Questions.
FAQs: Playwright Basic Commands
What are Playwright basic commands?
Playwright basic commands are APIs used to control browsers, navigate pages, locate elements, perform actions, validate results, capture evidence, and run automated tests.
How do I get started with Playwright commands?
Install Playwright with npm init playwright@latest, select TypeScript, install the required browsers, create a test, and run it with npx playwright test.
What are the most important Playwright commands for beginners?
Start with page.goto(), getByRole(), getByLabel(), locator(), click(), fill(), check(), selectOption(), expect(), and page.screenshot().
What is the basic Playwright TypeScript syntax?
A typical test uses:
import { test, expect } from ‘@playwright/test’;
test(‘basic test’, async ({ page }) => {
await page.goto(‘https://example.com’);
await expect(page).toHaveTitle(/Example/);
});
Is Playwright easier than Selenium for beginners?
Many beginners find Playwright convenient because it provides modern locators, auto-waiting, built-in assertions, browser isolation, tracing, and an integrated test runner. However, learning automation fundamentals remains important regardless of the framework.
Are Playwright commands only for UI testing?
No. Playwright also supports API testing, browser contexts, authentication workflows, network control, tracing, and other automation capabilities.
