### Install Browsers and System Dependencies Together Source: https://devdocs.io/playwright/browsers Combines browser installation and system dependency installation into a single command, streamlining the setup process for a specified browser. ```bash npx playwright install --with-deps chromium ``` -------------------------------- ### Global Setup with Trace Capturing on Failure Source: https://devdocs.io/playwright/test-global-setup-teardown This snippet shows how to capture a trace of failures that occur during global setup. By wrapping the setup logic in a `try...catch` block, tracing can be started before potential errors and stopped with a trace file path in both the success and error paths. This aids in debugging setup issues. ```typescript import { chromium, type FullConfig } from '@playwright/test'; async function globalSetup(config: FullConfig) { const { baseURL, storageState } = config.projects[0].use; const browser = await chromium.launch(); const context = await browser.newContext(); const page = await context.newPage(); try { // Start tracing with screenshots and snapshots await context.tracing.start({ screenshots: true, snapshots: true }); await page.goto(baseURL!); await page.getByLabel('User Name').fill('user'); await page.getByLabel('Password').fill('password'); await page.getByText('Sign in').click(); // Save storage state await context.storageState({ path: storageState as string }); // Stop tracing and save the trace file on success await context.tracing.stop({ path: './test-results/setup-trace.zip', }); await browser.close(); } catch (error) { // Stop tracing and save trace file on error await context.tracing.stop({ path: './test-results/failed-setup-trace.zip', }); await browser.close(); throw error; // Re-throw the error } } export default globalSetup; ``` -------------------------------- ### Run Example Playwright Tests Source: https://devdocs.io/playwright/index Commands to execute the example tests included with Playwright. Tests run headless by default across multiple browsers. Options are available to run in headed mode, target specific projects, or filter tests. ```shell npx playwright test ``` ```shell yarn playwright test ``` ```shell pnpm exec playwright test ``` -------------------------------- ### Install Playwright using npm, yarn, or pnpm Source: https://devdocs.io/playwright/index These commands initialize a new Playwright project or add Playwright to an existing one. The process involves selecting the language (TypeScript/JavaScript), test folder name, GitHub Actions integration, and browser installation. ```shell npm init playwright@latest ``` ```shell yarn create playwright ``` ```shell pnpm create playwright ``` -------------------------------- ### Playwright Configuration with Setup Project (TypeScript) Source: https://devdocs.io/playwright/auth This TypeScript configuration for Playwright sets up a 'setup' project that runs test files matching '.*\.setup\.ts'. It then defines 'chromium' and 'firefox' projects that depend on the 'setup' project and utilize the saved authentication state ('playwright/.auth/user.json'). This ensures tests start with an authenticated session. Dependencies include 'export default defineConfig' and 'devices' from '@playwright/test'. ```typescript import { defineConfig, devices } from '@playwright/test'; export default defineConfig({ projects: [ // Setup project { name: 'setup', testMatch: /.*\.setup\.ts/ }, { name: 'chromium', use: { ...devices['Desktop Chrome'], // Use prepared auth state. storageState: 'playwright/.auth/user.json', }, dependencies: ['setup'], }, { name: 'firefox', use: { ...devices['Desktop Firefox'], // Use prepared auth state. storageState: 'playwright/.auth/user.json', }, dependencies: ['setup'], }, ], }); ``` -------------------------------- ### Global Setup for Environment Variables Source: https://devdocs.io/playwright/test-global-setup-teardown This example illustrates how to make arbitrary data available in your Playwright tests by setting environment variables during global setup. Data can be simple strings or complex JSON objects. Tests can then access these environment variables via `process.env`. ```typescript import type { FullConfig } from '@playwright/test'; async function globalSetup(config: FullConfig) { // Set a simple string environment variable process.env.FOO = 'some data'; // Set a complex data structure as JSON string process.env.BAR = JSON.stringify({ some: 'data' }); } export default globalSetup; ``` ```typescript import { test } from '@playwright/test'; test('test', async ({ page }) => { // Environment variables set in globalSetup are available here const { FOO, BAR } = process.env; // Assertions to verify environment variables are populated expect(FOO).toEqual('some data'); const complexData = JSON.parse(BAR); expect(complexData).toEqual({ some: 'data' }); }); ``` -------------------------------- ### GitHub Actions Workflow for Playwright Tests Source: https://devdocs.io/playwright/ci-intro This YAML workflow automates the execution of Playwright tests on GitHub Actions. It checks out the code, sets up Node.js, installs dependencies, installs Playwright browsers, runs the tests, and uploads the generated report as an artifact. This workflow is triggered on pushes and pull requests to the main/master branches. ```yaml name: Playwright Tests on: push: branches: [ main, master ] pull_request: branches: [ main, master ] jobs: test: timeout-minutes: 60 runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - uses: actions/setup-node@v5 with: node-version: lts/* - name: Install dependencies run: npm ci - name: Install Playwright Browsers run: npx playwright install --with-deps - name: Run Playwright tests run: npx playwright test - uses: actions/upload-artifact@v4 if: ${{ !cancelled() }} with: name: playwright-report path: playwright-report/ retention-days: 30 ``` -------------------------------- ### Example Electron Automation Script with Playwright Source: https://devdocs.io/playwright/api/class-electron This comprehensive example demonstrates launching an Electron app, evaluating code within its context, interacting with its window, and then closing the app. It utilizes Playwright's API for Electron automation. Ensure Playwright is installed and Electron app is correctly configured. ```javascript const { _electron: electron } = require('playwright'); (async () => { // Launch Electron app. const electronApp = await electron.launch({ args: ['main.js'] }); // Evaluation expression in the Electron context. const appPath = await electronApp.evaluate(async ({ app }) => { // This runs in the main Electron process, parameter here is always // the result of the require('electron') in the main app script. return app.getAppPath(); }); console.log(appPath); // Get the first window that the app opens, wait if necessary. const window = await electronApp.firstWindow(); // Print the title. console.log(await window.title()); // Capture a screenshot. await window.screenshot({ path: 'intro.png' }); // Direct Electron console to Node terminal. window.on('console', console.log); // Click button. await window.click('text=Click me'); // Exit app. await electronApp.close(); })(); ``` -------------------------------- ### Start Selenium Node with Grid URL Source: https://devdocs.io/playwright/selenium-grid This command starts a Selenium node and registers it with a Selenium Grid Hub. The `SE_NODE_GRID_URL` environment variable must point to the hub's address, ensuring the node can connect to the grid. This is necessary for distributed Selenium Grid setups. ```bash SE_NODE_GRID_URL="http://:4444" java -jar selenium-server-.jar node ``` -------------------------------- ### Playwright Component Testing Setup (Svelte) Source: https://devdocs.io/playwright/test-components Provides an example of component testing for Svelte components using Playwright. It leverages the `mount` fixture from `@playwright/experimental-ct-svelte` to render Svelte components and verify their rendered output. Props can be passed to the Svelte component during mounting. ```javascript import { test, expect } from '@playwright/experimental-ct-svelte'; import HelloWorld from './HelloWorld.svelte'; test.use({ viewport: { width: 500, height: 500 } }); test('should work', async ({ mount }) => { const component = await mount(HelloWorld, { props: { msg: 'Greetings', }, }); await expect(component).toContainText('Greetings'); }); ``` -------------------------------- ### Check Playwright Version Source: https://devdocs.io/playwright/browsers Displays the currently installed version of Playwright. This command is useful for verifying your Playwright setup or when troubleshooting compatibility issues. ```bash npx playwright --version ``` -------------------------------- ### Create Setup Test - TypeScript Source: https://devdocs.io/playwright/test-global-setup-teardown Defines a setup test using Playwright's 'test' function aliased as 'setup'. This function is intended for initializing resources, like a database, before other tests run. ```typescript import { test as setup } from '@playwright/test'; setup('create new database', async ({ }) => { console.log('creating new database...'); // Initialize the database }); ``` -------------------------------- ### Update Playwright and Browser Binaries Source: https://devdocs.io/playwright/index Update the Playwright library to the latest version and download the necessary browser binaries and their dependencies. This process can be executed using npm, yarn, or pnpm. ```bash npm install -D @playwright/test@latest npx playwright install --with-deps ``` ```bash yarn add --dev @playwright/test@latest yarn playwright install --with-deps ``` ```bash pnpm install --save-dev @playwright/test@latest pnpm exec playwright install --with-deps ``` -------------------------------- ### Define Project with Setup Dependency - TypeScript Source: https://devdocs.io/playwright/test-global-setup-teardown Configure Playwright to match a setup file for a project. This allows defining specific files that should be treated as setup scripts for a given project. ```typescript import { defineConfig } from '@playwright/test'; export default defineConfig({ testDir: './tests', // ... projects: [ { name: 'setup db', testMatch: /global\.setup\.ts/, }, // { // other project // } ] }); ``` -------------------------------- ### Playwright Component Testing Setup (Vue) Source: https://devdocs.io/playwright/test-components Illustrates component testing for Vue applications with Playwright. It utilizes the `mount` fixture from `@playwright/experimental-ct-vue` to render Vue components and assert their content. The example shows passing props to the mounted component. ```javascript import { test, expect } from '@playwright/experimental-ct-vue'; import HelloWorld from './HelloWorld.vue'; test.use({ viewport: { width: 500, height: 500 } }); test('should work', async ({ mount }) => { const component = await mount(HelloWorld, { props: { msg: 'Greetings', }, }); await expect(component).toContainText('Greetings'); }); ``` -------------------------------- ### Traditional Test Setup (JavaScript) Source: https://devdocs.io/playwright/test-fixtures Demonstrates a traditional test setup using before/after hooks for managing the test environment. It instantiates the TodoPage class and performs setup and teardown operations. This approach can lead to repetitive setup logic across tests. ```javascript const { test } = require('@playwright/test'); const { TodoPage } = require('./todo-page'); test.describe('todo tests', () => { let todoPage; test.beforeEach(async ({ page }) => { todoPage = new TodoPage(page); await todoPage.goto(); await todoPage.addToDo('item1'); await todoPage.addToDo('item2'); }); test.afterEach(async () => { await todoPage.removeAll(); }); test('should add an item', async () => { await todoPage.addToDo('my item'); // ... }); test('should remove an item', async () => { await todoPage.remove('item1'); // ... }); }); ``` -------------------------------- ### Define Playwright Project Dependencies Source: https://devdocs.io/playwright/test-projects Sets up project dependencies where certain projects must run before others. This example configures 'chromium', 'firefox', and 'webkit' projects to depend on a 'setup' project. ```typescript import { defineConfig, devices } from '@playwright/test'; export default defineConfig({ projects: [ { name: 'setup', testMatch: '**/*.setup.ts', }, { name: 'chromium', use: { ...devices['Desktop Chrome'] }, dependencies: ['setup'], }, { name: 'firefox', use: { ...devices['Desktop Firefox'] }, dependencies: ['setup'], }, { name: 'webkit', use: { ...devices['Desktop Safari'] }, dependencies: ['setup'], }, ], }); ``` -------------------------------- ### Install Specific Browsers on CI (bash) Source: https://devdocs.io/playwright/best-practices Optimize browser downloads on Continuous Integration (CI) by installing only the necessary browsers. This reduces download time and disk space usage compared to installing all browsers. ```bash # Instead of installing all browsers npx playwright install --with-deps # Install only Chromium npx playwright install chromium --with-deps ``` -------------------------------- ### Install Playwright Browsers Source: https://devdocs.io/playwright/library Downloads the necessary Playwright browser binaries. This can be done explicitly using `npx playwright install` or automatically by installing helper packages like `@playwright/browser-chromium` during `npm install`. ```bash # Explicitly download browsers npx playwright install ``` ```bash # Use a helper package that downloads a browser on npm install npm install @playwright/browser-chromium ``` -------------------------------- ### POST /device/installApk Source: https://devdocs.io/playwright/api/class-androiddevice Installs an APK file onto the Android device, with optional arguments for the installation command. ```APIDOC ## POST /device/installApk ### Description Installs an apk on the device. ### Method POST ### Endpoint /device/installApk ### Parameters #### Request Body - **file** (string | Buffer) - Required - Either a path to the apk file, or apk file content. - **options** (Object) - Optional - **args** (Array) - Optional - Optional arguments to pass to the `shell:cmd package install` call. Defaults to `-r -t -S`. ### Request Example { "example": "{\"file\": \"/path/to/your/app.apk\", \"options\": { \"args\": [\"-r\"] }}" } ### Response #### Success Response (200) - **void** - Indicates successful installation. #### Response Example { "example": "" } ``` -------------------------------- ### Install Microsoft Edge Browser using Playwright CLI Source: https://devdocs.io/playwright/browsers This command installs the Microsoft Edge browser using the Playwright command-line interface. If the browser is not detected on your system, this command will download and install it. Note that this might override existing installations and is installed globally. ```bash npx playwright install msedge ``` -------------------------------- ### Install Playwright-Core Browsers using CLI Source: https://devdocs.io/playwright/release-notes Illustrates the updated command for installing browser binaries when using `playwright-core`. The binary name has changed from `playwright` to `playwright-core`, so the installation command is now `npx playwright-core install`. ```bash $ npx playwright-core install # the new way to install browsers when using playwright-core ``` -------------------------------- ### List Installed Playwright Browsers Source: https://devdocs.io/playwright/browsers Lists all Playwright browsers installed across all Playwright installations on the machine. This command is useful for auditing browser installations and disk space usage. It requires `npx` to be available, which comes with Node.js and npm. ```shell npx playwright install --list ``` -------------------------------- ### Install Playwright System Dependencies Source: https://devdocs.io/playwright/browsers Automatically installs necessary system dependencies for Playwright, particularly useful in CI environments. Dependencies for a single browser can also be installed. ```bash npx playwright install-deps ``` ```bash npx playwright install-deps chromium ``` -------------------------------- ### Install Playwright Browsers Source: https://devdocs.io/playwright/browsers Installs the default set of supported browsers for Playwright. You can also specify individual browsers like 'webkit' or view help for all options. ```bash npx playwright install ``` ```bash npx playwright install webkit ``` ```bash npx playwright install --help ``` -------------------------------- ### Install NPM Packages and Playwright Browsers Source: https://devdocs.io/playwright/ci Commands to install project dependencies using npm ci and then install Playwright browsers and their required system dependencies. This is a crucial step for running Playwright tests in CI environments. ```bash # Install NPM packages npm ci # Install Playwright browsers and dependencies npx playwright install --with-deps ``` -------------------------------- ### Specify Global Setup File in Playwright Source: https://devdocs.io/playwright/api/class-testconfig Sets the path to a global setup file that runs once before all tests in the suite. This file must export a single function that receives a FullConfig argument. Multiple setup files can be specified as an array. ```typescript import { defineConfig } from '@playwright/test'; export default defineConfig({ globalSetup: './global-setup', }); ``` -------------------------------- ### Launch Browser and Create Context with Device Emulation Source: https://devdocs.io/playwright/emulation This example shows how to launch a browser instance and create a new browser context with specific device emulation settings using Playwright's API. It imports the `chromium` and `devices` modules, launches Chrome, retrieves the 'iPhone 13' device configuration, and applies it to a new context. ```javascript const { chromium, devices } = require('playwright'); const browser = await chromium.launch(); const iphone13 = devices['iPhone 13']; const context = await browser.newContext({ ...iphone13, }); ``` -------------------------------- ### Write Basic Playwright Tests Source: https://devdocs.io/playwright/writing-tests This snippet demonstrates how to write basic Playwright tests in JavaScript. It includes navigating to a URL, asserting the page title, and interacting with a 'Get started' link, then verifying the visibility of an 'Installation' heading. It requires the Playwright test runner and its assertion library. ```javascript import { test, expect } from '@playwright/test'; test('has title', async ({ page }) => { await page.goto('https://playwright.dev/'); // Expect a title "to contain" a substring. await expect(page).toHaveTitle(/Playwright/); }); test('get started link', async ({ page }) => { await page.goto('https://playwright.dev/'); // Click the get started link. await page.getByRole('link', { name: 'Get started' }).click(); // Expects page to have a heading with the name of Installation. await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible(); }); ``` -------------------------------- ### PlaywrightDevPage Class Implementation (TypeScript) Source: https://devdocs.io/playwright/pom This TypeScript class encapsulates common operations for interacting with the playwright.dev page. It uses Playwright's Page and Locator objects to define and interact with page elements. Key methods include navigating to the site, clicking 'Get started', and navigating to the Page Object Model guide. ```typescript import { expect, type Locator, type Page } from '@playwright/test'; export class PlaywrightDevPage { readonly page: Page; readonly getStartedLink: Locator; readonly gettingStartedHeader: Locator; readonly pomLink: Locator; readonly tocList: Locator; constructor(page: Page) { this.page = page; this.getStartedLink = page.locator('a', { hasText: 'Get started' }); this.gettingStartedHeader = page.locator('h1', { hasText: 'Installation' }); this.pomLink = page.locator('li', { hasText: 'Guides', }).locator('a', { hasText: 'Page Object Model', }); this.tocList = page.locator('article div.markdown ul > li > a'); } async goto() { await this.page.goto('https://playwright.dev'); } async getStarted() { await this.getStartedLink.first().click(); await expect(this.gettingStartedHeader).toBeVisible(); } async pageObjectModel() { await this.getStarted(); await this.pomLink.click(); } } ``` -------------------------------- ### Setup and Teardown GitHub Repository with Playwright Source: https://devdocs.io/playwright/api-testing Shows how to use `beforeAll` and `afterAll` hooks with Playwright's request fixture to create a repository before tests run and delete it afterwards. This ensures a clean test environment. Assumes REPO and USER variables are defined. ```javascript test.beforeAll(async ({ request }) => { // Create a new repository const response = await request.post('/user/repos', { data: { name: REPO } }); expect(response.ok()).toBeTruthy(); }); test.afterAll(async ({ request }) => { // Delete the repository const response = await request.delete(`/repos/${USER}/${REPO}`); expect(response.ok()).toBeTruthy(); }); ``` -------------------------------- ### Global Setup for Authentication State Source: https://devdocs.io/playwright/test-global-setup-teardown This snippet demonstrates how to perform a global setup to authenticate a user once and reuse the authentication state across multiple tests. It utilizes Playwright's `baseURL` and `storageState` configuration options. Ensure `globalSetup`, `baseURL`, and `storageState` are correctly specified in your Playwright configuration file. ```typescript import { chromium, type FullConfig } from '@playwright/test'; async function globalSetup(config: FullConfig) { const { baseURL, storageState } = config.projects[0].use; const browser = await chromium.launch(); const page = await browser.newPage(); await page.goto(baseURL!); // Navigate to the base URL await page.getByLabel('User Name').fill('user'); // Fill username await page.getByLabel('Password').fill('password'); // Fill password await page.getByText('Sign in').click(); // Click sign in button // Save authentication state to a file await page.context().storageState({ path: storageState as string }); await browser.close(); // Close the browser } export default globalSetup; ``` ```typescript import { defineConfig } from '@playwright/test'; export default defineConfig({ globalSetup: require.resolve('./global-setup'), // Path to the global setup file use: { baseURL: 'http://localhost:3000/', // Base URL for tests storageState: 'state.json', // File to store authentication state }, }); ``` ```typescript import { test } from '@playwright/test'; test('test', async ({ page }) => { await page.goto('/'); // You are signed in! }); ``` -------------------------------- ### Get TestStep Start Time - Playwright Source: https://devdocs.io/playwright/api/class-teststep Retrieves the start time of the test step as a Date object. This is useful for measuring durations and correlating events within a test run. ```javascript testStep.startTime ``` -------------------------------- ### Enable Playwright Tracing Source: https://devdocs.io/playwright/release-notes Example of how to start tracing browser actions using the `browserContext.tracing` API. This allows capturing DOM snapshots, screenshots, and network activity for debugging. Tracing must be started before page navigation and stopped to export the trace. ```typescript const browser = await chromium.launch(); const context = await browser.newContext(); // Start tracing before creating / navigating a page. await context.tracing.start({ screenshots: true, snapshots: true }); const page = await context.newPage(); await page.goto('https://playwright.dev'); // Stop tracing and export it into a zip archive. await context.tracing.stop({ path: 'trace.zip' }); ``` -------------------------------- ### Playwright Component Testing Setup (React) Source: https://devdocs.io/playwright/test-components Demonstrates the setup for component testing with React using Playwright. It imports necessary testing utilities and mounts a React component for testing. The `mount` fixture is provided by `@playwright/experimental-ct-react`. ```javascript import { test, expect } from '@playwright/experimental-ct-react'; import HelloWorld from './HelloWorld'; test.use({ viewport: { width: 500, height: 500 } }); test('should work', async ({ mount }) => { const component = await mount(); await expect(component).toContainText('Greetings'); }); ``` -------------------------------- ### Record with Custom Setup using page.pause() Source: https://devdocs.io/playwright/codegen This JavaScript snippet demonstrates how to set up a custom recording environment for Playwright Codegen. It launches a non-headless browser, configures a browser context with custom routing, and then pauses the page to allow manual recording initiation via codegen controls. This is useful for non-standard setups like using `browserContext.route()`. ```javascript const { chromium } = require('@playwright/test'); (async () => { // Make sure to run headed. const browser = await chromium.launch({ headless: false }); // Setup context however you like. const context = await browser.newContext({ /* pass any options */ }); await context.route('**/*', route => route.continue()); // Pause the page, and start recording manually. const page = await context.newPage(); await page.pause(); })(); ``` -------------------------------- ### Azure Pipelines: Run Playwright Tests Source: https://devdocs.io/playwright/ci Configures an Azure Pipelines job to set up Node.js, install dependencies, install Playwright browsers, and run Playwright tests. This setup is suitable for Linux agents and uses a script-based approach to manage the Playwright execution within the pipeline. ```yaml trigger: - main pool: vmImage: ubuntu-latest steps: - task: UseNode@1 inputs: version: '22' displayName: 'Install Node.js' - script: npm ci displayName: 'npm ci' - script: npx playwright install --with-deps displayName: 'Install Playwright browsers' - script: npx playwright test displayName: 'Run Playwright tests' env: CI: 'true' ``` -------------------------------- ### Component Test: Sign-in Example (Testing Library vs. Playwright) Source: https://devdocs.io/playwright/testing-library Compares a typical sign-in test using Testing Library with its equivalent in Playwright Test for React. It shows how to set up, perform actions like typing and clicking, and verify the outcome. ```javascript import React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; test('sign in', async () => { // Setup the page. const user = userEvent.setup(); render(); // Perform actions. await user.type(screen.getByLabelText('Username'), 'John'); await user.type(screen.getByLabelText('Password'), 'secret'); await user.click(screen.getByRole('button', { name: 'Sign in' })); // Verify signed in state by waiting until "Welcome" message appears. expect(await screen.findByText('Welcome, John')).toBeInTheDocument(); }); ``` ```javascript const { test, expect } = require('@playwright/experimental-ct-react'); // 1 test('sign in', async ({ mount }) => { // 2 // Setup the page. const component = await mount(); // 3 // Perform actions. await component.getByLabel('Username').fill('John'); // 4 await component.getByLabel('Password').fill('secret'); await component.getByRole('button', { name: 'Sign in' }).click(); // Verify signed in state by waiting until "Welcome" message appears. await expect(component.getByText('Welcome, John')).toBeVisible(); // 5 }); ``` -------------------------------- ### Get Response Status Code (Playwright) Source: https://devdocs.io/playwright/api/class-apiresponse Retrieves the HTTP status code of the response. For example, 200 for a successful request, 404 for not found, etc. ```javascript apiResponse.status(); ``` -------------------------------- ### Get Test Title Path - Playwright Source: https://devdocs.io/playwright/api/class-testinfo Retrieves the full title path of the test, starting with the test file name. This property is an array of strings. ```javascript testInfo.titlePath ``` -------------------------------- ### Component Test Setup Script Placeholder Source: https://devdocs.io/playwright/test-components A placeholder comment indicating where to add setup logic for Playwright component tests. This script can be used to apply themes, inject global styles, or provide runtime dependencies to the component under test. ```javascript // Apply theme here, add anything your component needs at runtime here. ``` -------------------------------- ### Retrieve ConsoleMessage Page Source: https://devdocs.io/playwright/api/class-consolemessage This example shows how to get the Page object that generated a specific console message using Playwright's ConsoleMessage API. ```javascript consoleMessage.page(); // Returns: null | Page ``` -------------------------------- ### Running Playwright Tests with CLI Source: https://devdocs.io/playwright/test-cli This snippet demonstrates the basic syntax and common examples for running Playwright tests via the command line. It covers running all tests, specific files or directories, and filtering tests by line number or title. It also shows how to run tests in headed mode, for specific projects, and how to access help. ```bash npx playwright test [options] [test-filter...] # Run all tests npx playwright test # Run a single test file npx playwright test tests/todo-page.spec.ts # Run a set of test files npx playwright test tests/todo-page/ tests/landing-page/ # Run tests at a specific line npx playwright test my-spec.ts:42 # Run tests by title npx playwright test -g "add a todo item" # Run tests in headed browsers npx playwright test --headed # Run tests for a specific project npx playwright test --project=chromium # Get help npx playwright test --help ``` -------------------------------- ### Launch Browser and Interact with Page using Playwright Library Source: https://devdocs.io/playwright/library Demonstrates how to use the Playwright Library to launch a browser, create a new context with specific device settings, navigate to a URL, and assert the page title. It also shows how to intercept and abort JPG requests. This example is suitable for end-to-end testing scenarios where direct browser control is needed. ```typescript import { chromium, devices } from 'playwright'; import assert from 'node:assert'; (async () => { // Setup const browser = await chromium.launch(); const context = await browser.newContext(devices['iPhone 11']); const page = await context.newPage(); // The actual interesting bit await context.route('**.jpg', route => route.abort()); await page.goto('https://example.com/'); assert(await page.title() === 'Example Domain'); // 👎 not a Web First assertion // Teardown await context.close(); await browser.close(); })(); ``` ```javascript const assert = require('node:assert'); const { chromium, devices } = require('playwright'); (async () => { // Setup const browser = await chromium.launch(); const context = await browser.newContext(devices['iPhone 11']); const page = await context.newPage(); // The actual interesting bit await context.route('**.jpg', route => route.abort()); await page.goto('https://example.com/'); assert(await page.title() === 'Example Domain'); // 👎 not a Web First assertion // Teardown await context.close(); await browser.close(); })(); ``` -------------------------------- ### Get ARIA Snapshot Example with HTML Source: https://devdocs.io/playwright/api/class-locator Illustrates the ARIA snapshot output for a given HTML structure. The ARIA snapshot uses YAML markup to represent elements, roles, and their accessible names. ```html
  • Home
  • About
    • ``` ```yaml - list "Links": - listitem: - link "Home" - listitem: - link "About" ``` -------------------------------- ### Serve Playwright HTML Report Locally Source: https://devdocs.io/playwright/ci-intro This command serves the Playwright HTML report from a specified directory, allowing it to be viewed in a web browser. Ensure you are in the directory containing the extracted report before execution. ```bash npx playwright show-report name-of-my-extracted-playwright-report ``` -------------------------------- ### Install Playwright Test for Components (npm, yarn, pnpm) Source: https://devdocs.io/playwright/test-components Commands to install Playwright Test for component testing across different package managers. This command initializes Playwright and configures it for component testing. ```bash npm init playwright@latest -- --ct ``` ```bash yarn create playwright --ct ``` ```bash pnpm create playwright --ct ``` -------------------------------- ### Run Selenium Standalone Docker Container Source: https://devdocs.io/playwright/selenium-grid Start a Selenium standalone Chromium Docker container. This container acts as both the hub and the node, simplifying setup for basic testing. It exposes port 4444 for communication. ```bash docker run -d -p 4444:4444 --shm-size="2g" -e SE_NODE_GRID_URL="http://localhost:4444" selenium/standalone-chromium:latest ``` -------------------------------- ### Configure Global Setup and Teardown - TypeScript Source: https://devdocs.io/playwright/test-global-setup-teardown Configures Playwright to use external files for global setup and teardown operations. 'globalSetup' runs once before all tests, and 'globalTeardown' runs once after all tests complete. Data can be passed via environment variables. ```typescript import { defineConfig } from '@playwright/test'; export default defineConfig({ globalSetup: require.resolve('./global-setup'), globalTeardown: require.resolve('./global-teardown'), }); ``` -------------------------------- ### Build Custom Playwright Docker Image Source: https://devdocs.io/playwright/docker This Dockerfile outlines the steps to build a custom Docker image for running Playwright. It starts with a Node.js base image and then uses `npx` to install Playwright and its browser dependencies. ```dockerfile FROM node:20-bookworm RUN npx -y playwright@1.57.0 install --with-deps ``` -------------------------------- ### Running Playwright Component Tests Source: https://devdocs.io/playwright/test-components This command initiates the component testing suite for your project using npm. Ensure your `package.json` is configured with the appropriate test script. ```bash npm run test-ct ``` -------------------------------- ### Playwright beforeEach Hook for Test Isolation Source: https://devdocs.io/playwright/best-practices This example demonstrates using the `test.beforeEach` hook in Playwright to perform actions before each test, such as navigating to a login page and authenticating. This ensures each test starts from a consistent, isolated state. ```javascript import { test } from '@playwright/test'; test.beforeEach(async ({ page }) => { // Runs before each test and signs in each page. await page.goto('https://github.com/login'); await page.getByLabel('Username or email address').fill('username'); await page.getByLabel('Password').fill('password'); await page.getByRole('button', { name: 'Sign in' }).click(); }); test('first', async ({ page }) => { // page is signed in. }); test('second', async ({ page }) => { // page is signed in. }); ``` -------------------------------- ### Playwright AndroidInput API: drag Method Source: https://devdocs.io/playwright/api/class-androidinput Performs a drag gesture on an Android device from a starting point to an ending point with a specified number of steps. Requires Playwright to be installed and configured for Android automation. ```javascript await androidInput.drag({ x: fromX, y: fromY }, { x: toX, y: toY }, steps); ``` -------------------------------- ### Initializing Playwright Test Project Source: https://devdocs.io/playwright/release-notes These commands show how to initialize a new Playwright Test project. They can be run from the project's root directory or used to create a completely new project. This will set up necessary configuration files, example tests, and potentially a GitHub Actions workflow. ```bash # Run from your project's root directory npm init playwright@latest # Or create a new project npm init playwright@latest new-project ``` -------------------------------- ### Manual Browser Context Creation in Playwright Source: https://devdocs.io/playwright/browser-contexts Shows how to manually launch a browser and create a new isolated browser context and page. This approach is useful when not using Playwright as a dedicated test runner. ```javascript const { chromium } = require('playwright'); // Launch a browser instance const browser = await chromium.launch(); // Create a new isolated browser context const context = await browser.newContext(); // Create a new page within the context const page = await context.newPage(); ``` -------------------------------- ### Access ConsoleMessage Arguments Source: https://devdocs.io/playwright/api/class-consolemessage This example shows how to retrieve and process the arguments passed to a console message function using Playwright's ConsoleMessage API. It utilizes `args()` to get an array of JSHandle objects representing the arguments. ```javascript consoleMessage.args(); // Returns: Array ``` -------------------------------- ### Configure App with Hooks (React, Vue) Source: https://devdocs.io/playwright/test-components Explains how to use `beforeMount` and `afterMount` hooks to configure the application environment before or after a component is mounted. This is useful for setting up routers, fake servers, or passing custom configurations via `hooksConfig`. These hooks are supported in both React and Vue. ```typescript import { beforeMount, afterMount } from '@playwright/experimental-ct-react/hooks'; import { BrowserRouter } from 'react-router-dom'; export type HooksConfig = { enableRouting?: boolean; } beforeMount(async ({ App, hooksConfig }) => { if (hooksConfig?.enableRouting) return ; }); ``` ```typescript import { test, expect } from '@playwright/experimental-ct-react'; import type { HooksConfig } from '../playwright'; import { ProductsPage } from './pages/ProductsPage'; test('configure routing through hooks config', async ({ page, mount }) => { const component = await mount(, { hooksConfig: { enableRouting: true }, }); await expect(component.getByRole('link')).toHaveAttribute('href', '/products/42'); }); ``` ```typescript import { beforeMount, afterMount } from '@playwright/experimental-ct-vue/hooks'; import { router } from '../src/router'; export type HooksConfig = { enableRouting?: boolean; } beforeMount(async ({ app, hooksConfig }) => { if (hooksConfig?.enableRouting) app.use(router); }); ``` ```typescript import { test, expect } from '@playwright/experimental-ct-vue'; import type { HooksConfig } from '../playwright'; import ProductsPage from './pages/ProductsPage.vue'; test('configure routing through hooks config', async ({ page, mount }) => { const component = await mount(ProductsPage, { hooksConfig: { enableRouting: true }, }); await expect(component.getByRole('link')).toHaveAttribute('href', '/products/42'); }); ``` -------------------------------- ### Run Playwright Tests in UI Mode Source: https://devdocs.io/playwright/index Execute Playwright tests in UI Mode, which offers features like watch mode, live step view, and time travel debugging. This command can be run using npm, yarn, or pnpm. ```bash npx playwright test --ui ``` ```bash yarn playwright test --ui ``` ```bash pnpm exec playwright test --ui ``` -------------------------------- ### Playwright Tests Using PlaywrightDevPage (TypeScript) Source: https://devdocs.io/playwright/pom These Playwright tests demonstrate how to use the `PlaywrightDevPage` helper class in a TypeScript environment. They cover verifying the 'Get started' page content and navigating to the 'Page Object Model' article, showcasing typical end-to-end testing scenarios. ```typescript import { test, expect } from '@playwright/test'; import { PlaywrightDevPage } from './playwright-dev-page'; test('getting started should contain table of contents', async ({ page }) => { const playwrightDev = new PlaywrightDevPage(page); await playwrightDev.goto(); await playwrightDev.getStarted(); await expect(playwrightDev.tocList).toHaveText([ `How to install Playwright`, `What's Installed`, `How to run the example test`, `How to open the HTML test report`, `Write tests using web first assertions, page fixtures and locators`, `Run single test, multiple tests, headed mode`, `Generate tests with Codegen`, `See a trace of your tests` ]); }); test('should show Page Object Model article', async ({ page }) => { const playwrightDev = new PlaywrightDevPage(page); await playwrightDev.goto(); await playwrightDev.pageObjectModel(); await expect(page.locator('article')).toContainText('Page Object Model is a common pattern'); }); ``` -------------------------------- ### Run Playwright Tests with a Specific Reporter Source: https://devdocs.io/playwright/test-reporters This command line example demonstrates how to run Playwright tests and specify a reporter using the --reporter flag. This is a quick way to test different reporters without modifying the configuration file. ```bash npx playwright test --reporter=line ``` -------------------------------- ### Setup Handler to Dismiss Newsletter Dialog Source: https://devdocs.io/playwright/api/class-page Sets up a handler to automatically dismiss a 'Sign up to the newsletter' dialog when it appears. The handler clicks the 'No thanks' button. This example demonstrates a common use case for addLocatorHandler to manage unexpected pop-ups. ```javascript await page.addLocatorHandler(page.getByText('Sign up to the newsletter'), async () => { await page.getByRole('button', { name: 'No thanks' }).click(); }); // Write the test as usual. await page.goto('https://example.com'); await page.getByRole('button', { name: 'Start here' }).click(); ``` -------------------------------- ### Testing a React Component with a Story Wrapper Source: https://devdocs.io/playwright/test-components Demonstrates how to test a React component using its dedicated story wrapper file. This example shows mounting the wrapper, simulating file input, and verifying the output based on the data passed from the wrapper. ```javascript import { test, expect } from '@playwright/experimental-ct-react'; import { InputMediaForTest } from './input-media.story.tsx'; test('changes the image', async ({ mount }) => { let mediaSelected: string | null = null; const component = await mount( { mediaSelected = mediaName; }} /> ); await component .getByTestId('imageInput') .setInputFiles('src/assets/logo.png'); await expect(component.getByAltText(/selected image/i)).toBeVisible(); await expect.poll(() => mediaSelected).toBe('logo.png'); }); ``` -------------------------------- ### Playwright Configuration: Cross-Browser Testing Setup Source: https://devdocs.io/playwright/best-practices Provides a configuration example for setting up Playwright to test across multiple browsers (Chromium, Firefox, WebKit) on desktop devices. This configuration is typically placed in the `playwright.config.ts` file and ensures broad browser compatibility for the application. ```typescript import { defineConfig, devices } from '@playwright/test'; export default defineConfig({ projects: [ { name: 'chromium', use: { ...devices['Desktop Chrome'] }, }, { name: 'firefox', use: { ...devices['Desktop Firefox'] }, }, { name: 'webkit', use: { ...devices['Desktop Safari'] }, }, ], }); ``` -------------------------------- ### Navigate with Relative Path using baseURL Source: https://devdocs.io/playwright/test-webserver Demonstrates how to use a relative path for navigation after setting a `baseURL` in the Playwright configuration. The `page.goto()` command will automatically prepend the `baseURL` to the provided relative path, simplifying test logic. ```typescript import { test } from '@playwright/test'; test('test', async ({ page }) => { // This will navigate to http://localhost:3000/login await page.goto('./login'); }); ``` -------------------------------- ### Playwright API Testing: Stand-alone Node.js Request Source: https://devdocs.io/playwright/release-notes Perform stand-alone API requests directly from Node.js without involving a Playwright page. This utilizes the `request` fixture provided by Playwright to send requests to API endpoints. Example demonstrates a GET request. ```typescript import { test, expect } from '@playwright/test'; test('context fetch', async ({ request }) => { // Do a GET request on behalf of page const response = await request.get('http://example.com/foo.json'); // ... }); ```