# Playwright Cheat Sheet: Commands and Code Examples

> A complete Playwright cheat sheet with categorized commands and clear code examples for navigation, actions, selectors, waits, and API tests.

Source: https://testdino.com/playwright-cheatsheet

---

Quick Reference

# Playwright Cheatsheet

A complete Playwright cheat sheet with categorized commands and clear code examples for navigation, actions, selectors, waits, and API tests.

 Search... ⌘K

## Search

Search for pages and resources

On this page

- Browser start and close
- Context management
- Page / tab management
- Page information
- Page assertions
- Navigation
- Element selection
- Waiting for element states
- Element state getters
- Element assertions
- Click / hover / drag and drop
- Input
- Form input
- Keyboard
- File upload and download
- Evaluate JavaScript
- Dialog / alert / prompt / confirm
- Cookies
- Viewport / window size
- Screenshots
- Test runner assertions
- Fixtures, describe, config
- Network interception
- Local storage and session
- Frame / iframe
- Multiple contexts and cookies
- API testing via UI
- Auto-wait and actionability
- Tracing, video, screenshots in config
- Codegen and recording
- Browser storage state
- Locator chaining and filtering
- Accessibility
- Test tags and annotations
- Reporters
- Parallel and serial
- Retry and flaky
- Global setup and teardown

JavaScript Python Java

## Browser start and close

Start real browsers like Chromium, Chrome, Edge, Firefox, or WebKit, then close them to free resources.

JavaScript

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

const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();

await browser.close();
```

```
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
 browser = p.chromium.launch()
 context = browser.new_context()
 page = context.new_page()

 browser.close()
```

```
import com.microsoft.playwright.*;

Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch();
BrowserContext context = browser.newContext();
Page page = context.newPage();

browser.close();
playwright.close();
```

## Context management

Create an isolated context for clean cookies and storage, then close it when done.

JavaScript

```
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.com');
await context.close();
```

```
context = browser.new_context()
page = context.new_page()
page.goto("https://example.com")
context.close()
```

```
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.navigate("https://example.com");
context.close();
```

## Page / tab management

Open a tab, wait for popups, list tabs, switch focus, close tabs, and confirm a tab is closed.

JavaScript

```
const page = await context.newPage();
const [popup] = await Promise.all([
 page.waitForEvent('popup'),
 page.click('a[target="_blank"]'),
]);
const pages = context.pages();
await page.close();
```

```
page = context.new_page()
with page.expect_popup() as popup_info:
 page.click('a[target="_blank"]')
popup = popup_info.value
pages = context.pages
page.close()
```

```
Page page = context.newPage();
Page popup = page.waitForPopup(() -> {
 page.click("a[target='_blank']");
});
List pages = context.pages();
page.close();
```

## Page information

Get current URL and page title information.

JavaScript

```
const url = page.url();
const title = await page.title();
```

```
url = page.url
title = page.title()
```

```
String url = page.url();
String title = page.title();
```

## Page assertions

Assert page URL and title with various matching options.

JavaScript

```
await expect(page).toHaveURL('https://example.com');
await expect(page).toHaveURL(/.*checkout/);
await expect(page).toHaveTitle('My Page');
await expect(page).toHaveTitle(/My.*/);
```

```
expect(page).to_have_url("https://example.com")
expect(page).to_have_url(re.compile(".*checkout"))
expect(page).to_have_title("My Page")
expect(page).to_have_title(re.compile("My.*"))
```

```
assertThat(page).hasURL("https://example.com");
assertThat(page).hasURL(Pattern.compile(".*checkout"));
assertThat(page).hasTitle("My Page");
assertThat(page).hasTitle(Pattern.compile("My.*"));
```

## Navigation

Navigate to URLs, reload pages, and control browser history.

JavaScript

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

```
page.goto("https://example.com")
page.go_back()
page.go_forward()
page.reload()
```

```
page.navigate("https://example.com");
page.goBack();
page.goForward();
page.reload();
```

## Element selection

Select elements using various locator strategies for reliable automation.

JavaScript

```
page.getByRole('button', { name: 'Submit' });
page.getByText('Welcome');
page.getByLabel('Email');
page.getByPlaceholder('Enter email');
page.getByTestId('submit-btn');
page.locator('.my-class');
page.locator('#my-id');
```

```
page.get_by_role("button", name="Submit")
page.get_by_text("Welcome")
page.get_by_label("Email")
page.get_by_placeholder("Enter email")
page.get_by_test_id("submit-btn")
page.locator(".my-class")
page.locator("#my-id")
```

```
page.getByRole(AriaRole.BUTTON,
 new Page.GetByRoleOptions().setName("Submit"));
page.getByText("Welcome");
page.getByLabel("Email");
page.getByPlaceholder("Enter email");
page.getByTestId("submit-btn");
page.locator(".my-class");
page.locator("#my-id");
```

## Waiting for element states

Wait for elements to be in specific states before interacting with them.

JavaScript

```
await page.locator('.spinner').waitFor({ state: 'visible' });
await page.locator('.spinner').waitFor({ state: 'hidden' });
await page.locator('.item').waitFor({ state: 'attached' });
await page.locator('.slow').waitFor({ timeout: 10000 });
```

```
page.locator(".spinner").wait_for(state="visible")
page.locator(".spinner").wait_for(state="hidden")
page.locator(".item").wait_for(state="attached")
page.locator(".slow").wait_for(timeout=10000)
```

```
page.locator(".spinner").waitFor(
 new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE));
page.locator(".spinner").waitFor(
 new Locator.WaitForOptions().setState(WaitForSelectorState.HIDDEN));
page.locator(".item").waitFor(
 new Locator.WaitForOptions().setState(WaitForSelectorState.ATTACHED));
page.locator(".slow").waitFor(
 new Locator.WaitForOptions().setTimeout(10000));
```

## Element state getters

Get various properties and states of elements for validation and debugging.

JavaScript

```
const visible = await page.locator('.el').isVisible();
const enabled = await page.locator('.el').isEnabled();
const checked = await page.locator('.el').isChecked();
const text = await page.locator('.el').textContent();
const value = await page.locator('input').inputValue();
const attr = await page.locator('.el').getAttribute('href');
```

```
visible = page.locator(".el").is_visible()
enabled = page.locator(".el").is_enabled()
checked = page.locator(".el").is_checked()
text = page.locator(".el").text_content()
value = page.locator("input").input_value()
attr = page.locator(".el").get_attribute("href")
```

```
boolean visible = page.locator(".el").isVisible();
boolean enabled = page.locator(".el").isEnabled();
boolean checked = page.locator(".el").isChecked();
String text = page.locator(".el").textContent();
String value = page.locator("input").inputValue();
String attr = page.locator(".el").getAttribute("href");
```

## Element assertions

Assert element states, content, and properties for comprehensive test validation.

JavaScript

```
await expect(page.locator('.el')).toBeVisible();
await expect(page.locator('.el')).toBeHidden();
await expect(page.locator('.el')).toBeEnabled();
await expect(page.locator('.el')).toBeDisabled();
await expect(page.locator('.el')).toHaveText('Hello');
await expect(page.locator('.el')).toContainText('Hel');
await expect(page.locator('.el')).toHaveAttribute('href', '/home');
await expect(page.locator('.el')).toHaveClass(/active/);
await expect(page.locator('.el')).toHaveCount(3);
```

```
expect(page.locator(".el")).to_be_visible()
expect(page.locator(".el")).to_be_hidden()
expect(page.locator(".el")).to_be_enabled()
expect(page.locator(".el")).to_be_disabled()
expect(page.locator(".el")).to_have_text("Hello")
expect(page.locator(".el")).to_contain_text("Hel")
expect(page.locator(".el")).to_have_attribute("href", "/home")
expect(page.locator(".el")).to_have_class(re.compile("active"))
expect(page.locator(".el")).to_have_count(3)
```

```
assertThat(page.locator(".el")).isVisible();
assertThat(page.locator(".el")).isHidden();
assertThat(page.locator(".el")).isEnabled();
assertThat(page.locator(".el")).isDisabled();
assertThat(page.locator(".el")).hasText("Hello");
assertThat(page.locator(".el")).containsText("Hel");
assertThat(page.locator(".el")).hasAttribute("href", "/home");
assertThat(page.locator(".el")).hasClass(Pattern.compile("active"));
assertThat(page.locator(".el")).hasCount(3);
```

## Click / hover / drag and drop

Perform mouse interactions including clicks, double-clicks, right-clicks, hover, and drag-and-drop.

JavaScript

```
await page.locator('#btn').click();
await page.locator('#btn').dblclick();
await page.locator('#btn').click({ button: 'right' });
await page.locator('#menu').hover();
await page.dragAndDrop('#source', '#target');
```

```
page.locator("#btn").click()
page.locator("#btn").dblclick()
page.locator("#btn").click(button="right")
page.locator("#menu").hover()
page.drag_and_drop("#source", "#target")
```

```
page.locator("#btn").click();
page.locator("#btn").dblclick();
page.locator("#btn").click(new Locator.ClickOptions().setButton(MouseButton.RIGHT));
page.locator("#menu").hover();
page.dragAndDrop("#source", "#target");
```

## Input

Type text, clear fields, and fill form inputs.

JavaScript

```
await page.locator('#name').fill('John');
await page.locator('#name').clear();
await page.locator('#name').pressSequentially('Hello', { delay: 100 });
```

```
page.locator("#name").fill("John")
page.locator("#name").clear()
page.locator("#name").press_sequentially("Hello", delay=100)
```

```
page.locator("#name").fill("John");
page.locator("#name").clear();
page.locator("#name").pressSequentially("Hello",
 new Locator.PressSequentiallyOptions().setDelay(100));
```

## Form input

Work with select dropdowns, checkboxes, and radio buttons.

JavaScript

```
await page.locator('select#color').selectOption('blue');
await page.locator('select#color').selectOption({ label: 'Blue' });
await page.locator('#agree').check();
await page.locator('#agree').uncheck();
await page.locator('#option-a').check();
```

```
page.locator("select#color").select_option("blue")
page.locator("select#color").select_option(label="Blue")
page.locator("#agree").check()
page.locator("#agree").uncheck()
page.locator("#option-a").check()
```

```
page.locator("select#color").selectOption("blue");
page.locator("select#color").selectOption(
 new SelectOption().setLabel("Blue"));
page.locator("#agree").check();
page.locator("#agree").uncheck();
page.locator("#option-a").check();
```

## Keyboard

Simulate keyboard input, shortcuts, and key combinations.

JavaScript

```
await page.keyboard.press('Enter');
await page.keyboard.press('Control+A');
await page.keyboard.type('Hello World');
await page.keyboard.down('Shift');
await page.keyboard.up('Shift');
```

```
page.keyboard.press("Enter")
page.keyboard.press("Control+A")
page.keyboard.type("Hello World")
page.keyboard.down("Shift")
page.keyboard.up("Shift")
```

```
page.keyboard().press("Enter");
page.keyboard().press("Control+A");
page.keyboard().type("Hello World");
page.keyboard().down("Shift");
page.keyboard().up("Shift");
```

## File upload and download

Handle file uploads via input elements and intercept file downloads.

JavaScript

```
await page.locator('input[type="file"]').setInputFiles('file.pdf');
await page.locator('input[type="file"]').setInputFiles([]);

const [download] = await Promise.all([
 page.waitForEvent('download'),
 page.click('#download-btn'),
]);
const path = await download.path();
```

```
page.locator('input[type="file"]').set_input_files("file.pdf")
page.locator('input[type="file"]').set_input_files([])

with page.expect_download() as download_info:
 page.click("#download-btn")
download = download_info.value
path = download.path()
```

```
page.locator("input[type='file']").setInputFiles(Paths.get("file.pdf"));
page.locator("input[type='file']").setInputFiles(new Path[0]);

Download download = page.waitForDownload(() -> {
 page.click("#download-btn");
});
Path path = download.path();
```

## Evaluate JavaScript

Execute JavaScript in the browser context and retrieve results.

JavaScript

```
const result = await page.evaluate(() => document.title);
const el = await page.evaluate(() => {
 return document.querySelector('.el').textContent;
});
await page.evaluate((name) => {
 localStorage.setItem('user', name);
}, 'John');
```

```
result = page.evaluate("document.title")
el = page.evaluate("document.querySelector('.el').textContent")
page.evaluate("name => localStorage.setItem('user', name)", "John")
```

```
String result = (String) page.evaluate("document.title");
String el = (String) page.evaluate(
 "document.querySelector('.el').textContent");
page.evaluate("name => localStorage.setItem('user', name)", "John");
```

## Dialog / alert / prompt / confirm

Handle browser dialogs including alerts, confirms, and prompts.

JavaScript

```
page.on('dialog', async dialog => {
 console.log(dialog.message());
 await dialog.accept(); // or dialog.dismiss()
});
// For prompt:
page.on('dialog', dialog => dialog.accept('my answer'));
```

```
def handle_dialog(dialog):
 print(dialog.message)
 dialog.accept() # or dialog.dismiss()

page.on("dialog", handle_dialog)
# For prompt:
page.on("dialog", lambda d: d.accept("my answer"))
```

```
page.onDialog(dialog -> {
 System.out.println(dialog.message());
 dialog.accept(); // or dialog.dismiss()
});
// For prompt:
page.onDialog(dialog -> dialog.accept("my answer"));
```

## Cookies

Get, set, and clear browser cookies within a context.

JavaScript

```
const cookies = await context.cookies();
await context.addCookies([{
 name: 'token', value: 'abc123',
 domain: '.example.com', path: '/'
}]);
await context.clearCookies();
```

```
cookies = context.cookies()
context.add_cookies([{
 "name": "token", "value": "abc123",
 "domain": ".example.com", "path": "/"
}])
context.clear_cookies()
```

```
List cookies = context.cookies();
context.addCookies(List.of(new Cookie("token", "abc123")
 .setDomain(".example.com").setPath("/")));
context.clearCookies();
```

## Viewport / window size

Set viewport dimensions and emulate device screen sizes.

JavaScript

```
const context = await browser.newContext({
 viewport: { width: 1280, height: 720 }
});
await page.setViewportSize({ width: 375, height: 812 });
```

```
context = browser.new_context(
 viewport={"width": 1280, "height": 720}
)
page.set_viewport_size({"width": 375, "height": 812})
```

```
BrowserContext context = browser.newContext(
 new Browser.NewContextOptions()
 .setViewportSize(1280, 720));
page.setViewportSize(375, 812);
```

## Screenshots

Capture full page or element screenshots.

JavaScript

```
await page.screenshot({ path: 'page.png' });
await page.screenshot({ path: 'full.png', fullPage: true });
await page.locator('.card').screenshot({ path: 'card.png' });
```

```
page.screenshot(path="page.png")
page.screenshot(path="full.png", full_page=True)
page.locator(".card").screenshot(path="card.png")
```

```
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("page.png")));
page.screenshot(new Page.ScreenshotOptions()
 .setPath(Paths.get("full.png")).setFullPage(true));
page.locator(".card").screenshot(
 new Locator.ScreenshotOptions().setPath(Paths.get("card.png")));
```

## Test runner assertions

Use Playwright Test's built-in expect assertions for robust test validation.

JavaScript

```
const { test, expect } = require('@playwright/test');

test('homepage has title', async ({ page }) => {
 await page.goto('https://example.com');
 await expect(page).toHaveTitle(/Example/);
 await expect(page.locator('h1')).toBeVisible();
});
```

```
from playwright.sync_api import expect

def test_homepage_title(page):
 page.goto("https://example.com")
 expect(page).to_have_title(re.compile("Example"))
 expect(page.locator("h1")).to_be_visible()
```

```
import static com.microsoft.playwright.assertions.PlaywrightAssertions.*;

@Test
void homepageHasTitle() {
 page.navigate("https://example.com");
 assertThat(page).hasTitle(Pattern.compile("Example"));
 assertThat(page.locator("h1")).isVisible();
}
```

## Fixtures, describe, config

Organize tests with fixtures, describe blocks, and before/after hooks.

JavaScript

```
const { test } = require('@playwright/test');

test.describe('Login flow', () => {
 test.beforeEach(async ({ page }) => {
 await page.goto('/login');
 });
 test.afterEach(async ({ page }) => {
 await page.close();
 });
 test('valid login', async ({ page }) => {
 // ...
 });
});
```

```
import pytest

@pytest.fixture(autouse=True)
def go_to_login(page):
 page.goto("/login")
 yield
 page.close()

def test_valid_login(page):
 # ...
 pass
```

```
@BeforeEach
void setUp() {
 page.navigate("/login");
}

@AfterEach
void tearDown() {
 page.close();
}

@Test
void validLogin() {
 // ...
}
```

## Network interception

Intercept, modify, and mock network requests and responses.

JavaScript

```
await page.route('**/api/users', route => {
 route.fulfill({
 status: 200,
 contentType: 'application/json',
 body: JSON.stringify([{ name: 'John' }]),
 });
});
await page.route('**/*.png', route => route.abort());
```

```
def handle_route(route):
 route.fulfill(
 status=200,
 content_type="application/json",
 body='[{"name": "John"}]',
 )

page.route("**/api/users", handle_route)
page.route("**/*.png", lambda route: route.abort())
```

```
page.route("**/api/users", route -> {
 route.fulfill(new Route.FulfillOptions()
 .setStatus(200)
 .setContentType("application/json")
 .setBody("[{\"name\": \"John\"}]"));
});
page.route("**/*.png", Route::abort);
```

## Local storage and session

Read and write localStorage and sessionStorage values.

JavaScript

```
await page.evaluate(() => {
 localStorage.setItem('key', 'value');
});
const val = await page.evaluate(() => {
 return localStorage.getItem('key');
});
```

```
page.evaluate("localStorage.setItem('key', 'value')")
val = page.evaluate("localStorage.getItem('key')")
```

```
page.evaluate("localStorage.setItem('key', 'value')");
String val = (String) page.evaluate("localStorage.getItem('key')");
```

## Frame / iframe

Interact with content inside iframes and nested frames.

JavaScript

```
const frame = page.frameLocator('#my-iframe');
await frame.locator('#btn').click();
await frame.locator('input').fill('Hello');
```

```
frame = page.frame_locator("#my-iframe")
frame.locator("#btn").click()
frame.locator("input").fill("Hello")
```

```
FrameLocator frame = page.frameLocator("#my-iframe");
frame.locator("#btn").click();
frame.locator("input").fill("Hello");
```

## Multiple contexts and cookies

Run multiple browser contexts simultaneously for multi-user testing.

JavaScript

```
const userCtx = await browser.newContext();
const adminCtx = await browser.newContext();
const userPage = await userCtx.newPage();
const adminPage = await adminCtx.newPage();
```

```
user_ctx = browser.new_context()
admin_ctx = browser.new_context()
user_page = user_ctx.new_page()
admin_page = admin_ctx.new_page()
```

```
BrowserContext userCtx = browser.newContext();
BrowserContext adminCtx = browser.newContext();
Page userPage = userCtx.newPage();
Page adminPage = adminCtx.newPage();
```

## API testing via UI

Make direct API requests using the Playwright request context.

JavaScript

```
const response = await page.request.get('/api/users');
expect(response.ok()).toBeTruthy();
const body = await response.json();

await page.request.post('/api/login', {
 data: { email: 'a@b.com', password: '123' }
});
```

```
response = page.request.get("/api/users")
assert response.ok
body = response.json()

page.request.post("/api/login", data={
 "email": "a@b.com", "password": "123"
})
```

```
APIResponse response = page.request().get("/api/users");
assertTrue(response.ok());

page.request().post("/api/login",
 RequestOptions.create()
 .setData(Map.of("email", "a@b.com", "password", "123")));
```

## Auto-wait and actionability

Understand Playwright's built-in auto-waiting and how to customize timeouts.

JavaScript

```
// Playwright auto-waits for elements by default
await page.locator('#btn').click(); // waits until actionable

// Custom timeout per action
await page.locator('#btn').click({ timeout: 5000 });

// Global timeout in config
// playwright.config.ts: timeout: 30000
```

```
# Playwright auto-waits for elements by default
page.locator("#btn").click() # waits until actionable

# Custom timeout per action
page.locator("#btn").click(timeout=5000)

# Global timeout in config
# conftest.py: pytest --timeout 30000
```

```
// Playwright auto-waits for elements by default
page.locator("#btn").click(); // waits until actionable

// Custom timeout per action
page.locator("#btn").click(
 new Locator.ClickOptions().setTimeout(5000));
```

## Tracing, video, screenshots in config

Enable trace recording, video capture, and automatic screenshots on failure.

JavaScript

```
// playwright.config.ts
module.exports = {
 use: {
 trace: 'on-first-retry',
 video: 'retain-on-failure',
 screenshot: 'only-on-failure',
 },
};
```

```
# conftest.py
@pytest.fixture(scope="session")
def browser_context_args():
 return {
 "record_video_dir": "videos/",
 }
```

```
// In test setup
context = browser.newContext(new Browser.NewContextOptions()
 .setRecordVideoDir(Paths.get("videos/")));

// Tracing
context.tracing().start(new Tracing.StartOptions()
 .setScreenshots(true).setSnapshots(true));
context.tracing().stop(new Tracing.StopOptions()
 .setPath(Paths.get("trace.zip")));
```

## Codegen and recording

Use Playwright's code generator to record user interactions as test scripts.

JavaScript

```
# Run from terminal
npx playwright codegen https://example.com

# With specific viewport
npx playwright codegen --viewport-size=1280,720 https://example.com

# With device emulation
npx playwright codegen --device="iPhone 13" https://example.com
```

```
# Run from terminal
playwright codegen https://example.com

# With specific viewport
playwright codegen --viewport-size=1280,720 https://example.com

# With device emulation
playwright codegen --device="iPhone 13" https://example.com
```

```
// Run from terminal
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI \
 -D exec.args="codegen https://example.com"
```

## Browser storage state

Save and reuse authentication state across tests to skip login flows.

JavaScript

```
// Save storage state
await context.storageState({ path: 'auth.json' });

// Reuse in new context
const context = await browser.newContext({
 storageState: 'auth.json'
});
```

```
# Save storage state
context.storage_state(path="auth.json")

# Reuse in new context
context = browser.new_context(storage_state="auth.json")
```

```
// Save storage state
context.storageState(
 new BrowserContext.StorageStateOptions().setPath(Paths.get("auth.json")));

// Reuse in new context
BrowserContext ctx = browser.newContext(
 new Browser.NewContextOptions().setStorageStatePath(Paths.get("auth.json")));
```

## Locator chaining and filtering

Chain and filter locators for precise element targeting.

JavaScript

```
page.locator('.list').locator('.item').first();
page.locator('.item').filter({ hasText: 'Buy' });
page.locator('.item').filter({ has: page.locator('.price') });
page.locator('.item').nth(2);
```

```
page.locator(".list").locator(".item").first
page.locator(".item").filter(has_text="Buy")
page.locator(".item").filter(has=page.locator(".price"))
page.locator(".item").nth(2)
```

```
page.locator(".list").locator(".item").first();
page.locator(".item").filter(
 new Locator.FilterOptions().setHasText("Buy"));
page.locator(".item").filter(
 new Locator.FilterOptions().setHas(page.locator(".price")));
page.locator(".item").nth(2);
```

## Accessibility

Run accessibility audits and check ARIA attributes.

JavaScript

```
const snapshot = await page.accessibility.snapshot();
console.log(snapshot);

await expect(page.locator('#btn')).toHaveAttribute('aria-label', 'Close');
await expect(page.locator('#nav')).toHaveRole('navigation');
```

```
snapshot = page.accessibility.snapshot()
print(snapshot)

expect(page.locator("#btn")).to_have_attribute("aria-label", "Close")
```

```
// Check ARIA attributes
assertThat(page.locator("#btn")).hasAttribute("aria-label", "Close");
```

## Test tags and annotations

Tag, skip, and annotate tests for selective execution.

JavaScript

```
test('fast test', { tag: '@fast' }, async ({ page }) => {});
test('slow test', { tag: '@slow' }, async ({ page }) => {});
test.skip('not ready', async ({ page }) => {});
test.fixme('known bug', async ({ page }) => {});

// Run: npx playwright test --grep @fast
```

```
import pytest

@pytest.mark.fast
def test_fast(page):
 pass

@pytest.mark.skip(reason="not ready")
def test_not_ready(page):
 pass

# Run: pytest -m fast
```

```
@Test
@Tag("fast")
void fastTest() { }

@Test
@Disabled("not ready")
void notReady() { }

// Run: mvn test -Dgroups=fast
```

## Reporters

Configure test reporters for HTML, JSON, and custom output formats.

JavaScript

```
// playwright.config.ts
module.exports = {
 reporter: [
 ['html', { open: 'never' }],
 ['json', { outputFile: 'results.json' }],
 ['list'],
 ['@testdino/playwright', { token: process.env.TESTDINO_TOKEN }],
 ],
};
```

```
# pytest.ini
# [pytest]
# addopts = --html=report.html --json=results.json
```

```
// Maven surefire plugin configuration
//
// html
// 
```

## Parallel and serial

Control test execution order - run tests in parallel or sequentially.

JavaScript

```
// Parallel (default)
test.describe.parallel('parallel suite', () => {
 test('test A', async ({ page }) => {});
 test('test B', async ({ page }) => {});
});

// Serial - tests depend on each other
test.describe.serial('serial suite', () => {
 test('step 1', async ({ page }) => {});
 test('step 2', async ({ page }) => {});
});
```

```
# Parallel: install pytest-xdist
# pytest -n auto

# Serial (default pytest behavior)
def test_step_1(page):
 pass

def test_step_2(page):
 pass
```

```
// JUnit 5 parallel config in junit-platform.properties
// junit.jupiter.execution.parallel.enabled=true
// junit.jupiter.execution.parallel.mode.default=concurrent

@Execution(ExecutionMode.SAME_THREAD) // serial
class SerialTests { }
```

## Retry and flaky

Configure test retries to handle flaky tests automatically.

JavaScript

```
// playwright.config.ts
module.exports = {
 retries: 2, // retry failed tests up to 2 times
 retries: process.env.CI ? 2 : 0, // only retry in CI
};

// Per-test retry
test('flaky test', { retries: 3 }, async ({ page }) => {});
```

```
# pytest.ini
# [pytest]
# addopts = --count=3 # with pytest-repeat

# Or use pytest-rerunfailures
# pip install pytest-rerunfailures
# pytest --reruns 2
```

```
// JUnit 5 with @RepeatedTest
@RepeatedTest(3)
void flakyTest() { }
```

## Global setup and teardown

Run setup and teardown scripts before/after all tests in the project.

JavaScript

```
// playwright.config.ts
module.exports = {
 globalSetup: require.resolve('./global-setup'),
 globalTeardown: require.resolve('./global-teardown'),
};

// global-setup.ts
async function globalSetup() {
 // seed database, start services, etc.
}
module.exports = globalSetup;
```

```
# conftest.py
import pytest

@pytest.fixture(scope="session", autouse=True)
def global_setup():
 # seed database, start services
 yield
 # teardown
```

```
// JUnit 5
@BeforeAll
static void globalSetup() {
 // seed database, start services
}

@AfterAll
static void globalTeardown() {
 // cleanup
}
```

## Keep going with Playwright

[### Playwright Interview Questions 79 questions with detailed answers on locators, fixtures, CI, debugging, and the AI ecosystem.Read more](https://testdino.com/playwright-interview-questions-answers-2026)

[### Playwright Dashboard See how TestDino reports, debugs, and analyzes Playwright test runs across your CI.Read more](https://testdino.com/playwright)

[### Free Playwright Tools Sharding calculator, CI cost estimator, config generator, and more for Playwright teams.Read more](https://testdino.com/tools)
