### Test 'getting started' page content (JavaScript)
Source: https://playwright.dev/docs/pom
Uses the PlaywrightDevPage POM to navigate to the 'Getting Started' section and verify the table of contents. Requires the PlaywrightDevPage class to be imported.
```javascript
const { PlaywrightDevPage } = require('./playwright-dev-page');
// In the test
const page = await browser.newPage();
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, fixtures and locators`,
`Run single or multiple tests; headed mode`,
`Generate tests with Codegen`,
`View a trace of your tests`,
]);
```
--------------------------------
### Accessing globalSetup
Source: https://playwright.dev/docs/api/class-fullconfig
Get the path to the global setup function. Refer to testConfig.globalSetup for more details.
```javascript
fullConfig.globalSetup
```
--------------------------------
### Optimize Browser Downloads on CI
Source: https://playwright.dev/docs/best-practices
Install only necessary browsers on CI to save download time and disk space. This example installs only Chromium.
```bash
# Instead of installing all browsers
npx playwright install --with-deps
# Install only Chromium
npx playwright install chromium --with-deps
```
--------------------------------
### Test 'getting started' page content (TypeScript)
Source: https://playwright.dev/docs/pom
Uses the PlaywrightDevPage POM to navigate to the 'Getting Started' section and verify the table of contents. Requires the PlaywrightDevPage class to be imported.
```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, fixtures and locators`,
`Run single or multiple tests; headed mode`,
`Generate tests with Codegen`,
`View a trace of your tests`,
]);
});
```
--------------------------------
### Define Setup Project
Source: https://playwright.dev/docs/test-global-setup-teardown
Define a project named 'setup db' that matches the global setup file.
```typescript
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests',
// ...
projects: [
{
name: 'setup db',
testMatch: /global\.setup\.ts/,
},
// {
// other project
// }
]
});
```
--------------------------------
### Install Browser and Dependencies Together
Source: https://playwright.dev/docs/browsers
Combine browser installation with system dependency installation using a single command.
```bash
npx playwright install --with-deps chromium
```
--------------------------------
### View Install Help
Source: https://playwright.dev/docs/browsers
This command displays help information for the 'install' command, listing all supported browsers.
```bash
npx playwright install --help
```
--------------------------------
### Global Setup for Authentication
Source: https://playwright.dev/docs/test-global-setup-teardown
This global setup script authenticates a user and saves the authentication state to a 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!);
await page.getByLabel('User Name').fill('user');
await page.getByLabel('Password').fill('password');
await page.getByText('Sign in').click();
await page.context().storageState({ path: storageState as string });
await browser.close();
}
export default globalSetup;
```
--------------------------------
### Global Setup Test
Source: https://playwright.dev/docs/test-global-setup-teardown
Create a setup test in `global.setup.ts` to initialize resources like a database.
```typescript
import { test as setup } from '@playwright/test';
setup('create new database', async ({ }) => {
console.log('creating new database...');
// Initialize the database
});
```
--------------------------------
### Next.js Component Test Setup with beforeMount
Source: https://playwright.dev/docs/release-notes
Configure your Next.js application for component tests using `beforeMount`. This example shows how to mock the router with test-specific query parameters.
```jsx
import { test } from '@playwright/experimental-ct-react';
import { Component } from './mycomponent';
test('should work', async ({ mount }) => {
const component = await mount(, {
// Pass mock value from test into `beforeMount`.
hooksConfig: {
router: {
query: { page: 1, per_page: 10 },
asPath: '/posts'
}
}
});
});
```
```javascript
import router from 'next/router';
import { beforeMount } from '@playwright/experimental-ct-react/hooks';
beforeMount(async ({ hooksConfig }) => {
// Before mount, redefine useRouter to return mock value from test.
router.useRouter = () => hooksConfig.router;
});
```
--------------------------------
### Example .env File Content
Source: https://playwright.dev/docs/test-parameterize
This is an example of a .env file content, showing how to define environment variables like STAGING, USER_NAME, and PASSWORD.
```dotenv
# .env file
STAGING=0
USER_NAME=me
PASSWORD=secret
```
--------------------------------
### Install All Browsers
Source: https://playwright.dev/docs/test-cli
Command to install all browsers supported by Playwright.
```bash
npx playwright install
```
--------------------------------
### Start Screencast to Record Video
Source: https://playwright.dev/docs/api/class-screencast
Use this snippet to start recording video to a specified file path. Ensure to call `screencast.stop()` afterwards to finalize the recording.
```javascript
await page.screencast.start({ path: 'video.webm', size: { width: 1280, height: 800 } });
// ... perform actions ...
await page.screencast.stop();
```
--------------------------------
### Install Specific Browser
Source: https://playwright.dev/docs/browsers
Use this command to install a particular browser, such as WebKit.
```bash
npx playwright install webkit
```
--------------------------------
### Global Setup with Trace Capture
Source: https://playwright.dev/docs/test-global-setup-teardown
Capture traces during global setup, including handling errors and stopping tracing appropriately.
```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 {
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();
await context.storageState({ path: storageState as string });
await context.tracing.stop({
path: './test-results/setup-trace.zip',
});
await browser.close();
} catch (error) {
await context.tracing.stop({
path: './test-results/failed-setup-trace.zip',
});
await browser.close();
throw error;
}
}
```
--------------------------------
### Configure Project Dependencies for Setup
Source: https://playwright.dev/docs/test-projects
Set up projects that depend on a common setup project. This ensures setup tasks run before dependent tests and allows for tracing and fixture usage in setup.
```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 Microsoft Edge using Playwright CLI
Source: https://playwright.dev/docs/browsers
Install Microsoft Edge using the Playwright command-line tool. This command installs the browser at the default global location, potentially overriding existing installations.
```bash
npx playwright install msedge
```
--------------------------------
### List All Installed Playwright Browsers
Source: https://playwright.dev/docs/browsers
Execute 'npx playwright install --list' to display a list of all Playwright browser versions installed on the machine across different installations.
```bash
npx playwright install --list
```
--------------------------------
### Install Multiple Specific Browsers
Source: https://playwright.dev/docs/test-cli
Command to install multiple specified browsers, such as Chromium and WebKit.
```bash
npx playwright install chromium webkit
```
--------------------------------
### Install Default Browsers
Source: https://playwright.dev/docs/browsers
Run this command to install the default set of browsers supported by Playwright.
```bash
npx playwright install
```
--------------------------------
### Install Browsers Command Syntax
Source: https://playwright.dev/docs/test-cli
Syntax for Playwright commands to install, install with dependencies, or uninstall browsers.
```bash
npx playwright install [options] [browser...]
npx playwright install-deps [options] [browser...]
npx playwright uninstall
```
--------------------------------
### Install Dependencies for a Single Browser
Source: https://playwright.dev/docs/browsers
Install system dependencies for a specific browser, like Chromium.
```bash
npx playwright install-deps chromium
```
--------------------------------
### Start Tracing with Options
Source: https://playwright.dev/docs/api/class-tracing
Starts tracing with specified options. Consider enabling tracing in your config file for more comprehensive traces that include test assertions.
```javascript
await context.tracing.start({ screenshots: true, snapshots: true });
```
--------------------------------
### Install Playwright Browsers
Source: https://playwright.dev/docs/library
Explicitly download the necessary Playwright browsers using the `install` command. This ensures you have the correct browser binaries for testing.
```bash
# Explicitly download browsers
npx playwright install
```
--------------------------------
### Keyboard Press Example with Navigation and Modifiers
Source: https://playwright.dev/docs/api/class-keyboard
Provides a comprehensive example of using `keyboard.press()` for various keys, including navigation and modifier shortcuts, along with screenshots.
```javascript
const page = await browser.newPage();
await page.goto('https://keycode.info');
await page.keyboard.press('A');
await page.screenshot({ path: 'A.png' });
await page.keyboard.press('ArrowLeft');
await page.screenshot({ path: 'ArrowLeft.png' });
await page.keyboard.press('Shift+O');
await page.screenshot({ path: 'O.png' });
await browser.close();
```
--------------------------------
### Install Playwright-Core Browsers
Source: https://playwright.dev/docs/release-notes
When using `playwright-core` directly, use the `playwright-core install` command to download browser binaries. This command replaces the older `playwright install` for `playwright-core` users.
```bash
$ npx playwright-core install # the new way to install browsers when using playwright-core
```
--------------------------------
### Install Browsers with Dependencies
Source: https://playwright.dev/docs/release-notes
Use this command to download browsers and their dependencies after installing Playwright. This is the recommended approach for CI environments.
```bash
- run: npm ci
- run: npx playwright install --with-deps
```
--------------------------------
### Install the virtual WebAuthn authenticator
Source: https://playwright.dev/docs/api/class-credentials
Installs the virtual WebAuthn authenticator into the context, overriding navigator.credentials.create() and navigator.credentials.get(). Call this before the page first touches navigator.credentials.
```javascript
await credentials.install();
```
--------------------------------
### Global Setup with Environment Variables
Source: https://playwright.dev/docs/test-global-setup-teardown
Set environment variables in global setup to make data available to tests.
```typescript
import type { FullConfig } from '@playwright/test';
async function globalSetup(config: FullConfig) {
process.env.FOO = 'some data';
// Or a more complicated data structure as JSON:
process.env.BAR = JSON.stringify({ some: 'data' });
}
export default globalSetup;
```
--------------------------------
### Install Specific Browser
Source: https://playwright.dev/docs/test-cli
Command to install only the Chromium browser.
```bash
npx playwright install chromium
```
--------------------------------
### Configure Web Server
Source: https://playwright.dev/docs/api/class-testconfig
Example of configuring a web server within Playwright Test. This setup allows Playwright to start and manage a server for your tests, waiting for it to become available before execution.
```typescript
import { defineConfig } from '@playwright/test';
export default defineConfig({
// ... other configurations
webServer: {
command: 'npm run start',
port: 3000,
// Optional: wait for a specific URL or pattern in stdout/stderr
// url: 'http://localhost:3000/health',
// wait: {
// stdout: /Server listening on port 3000/,
// },
// Optional: reuse existing server if available
// reuseExistingServer: !process.env.CI,
},
// ... other configurations
});
```
--------------------------------
### Configure Global Setup and Teardown
Source: https://playwright.dev/docs/test-global-setup-teardown
Set the paths to your global setup and teardown files in the Playwright configuration.
```typescript
import { defineConfig } from '@playwright/test';
export default defineConfig({
globalSetup: require.resolve('./global-setup'),
globalTeardown: require.resolve('./global-teardown'),
});
```
--------------------------------
### fullConfig.globalSetup
Source: https://playwright.dev/docs/api/class-fullconfig
Path to the global setup script. Corresponds to `testConfig.globalSetup`.
```APIDOC
## fullConfig.globalSetup
### Description
See testConfig.globalSetup.
### Type
* null | string
```
--------------------------------
### Authenticate using a Setup Project
Source: https://playwright.dev/docs/auth
Use this method in a setup project to authenticate once and save the state for subsequent tests. Replace the placeholder login request with your application's actual authentication endpoint and credentials.
```typescript
import { test as setup } from '@playwright/test';
const authFile = 'playwright/.auth/user.json';
setup('authenticate', async ({ request }) => {
// Send authentication request. Replace with your own.
await request.post('https://github.com/login', {
form: {
'user': 'user',
'password': 'password'
}
});
await request.storageState({ path: authFile });
});
```
--------------------------------
### Sending GET Request with URLSearchParams
Source: https://playwright.dev/docs/api/class-apirequestcontext
This example demonstrates sending a GET request using URLSearchParams for query parameters. It allows for multiple values for the same parameter key.
```javascript
const searchParams = new URLSearchParams();
searchParams.set('isbn', '1234');
searchParams.append('page', 23);
searchParams.append('page', 24);
await request.get('https://example.com/api/getText', { params: searchParams });
```
--------------------------------
### Basic Azure Pipelines Setup for Playwright
Source: https://playwright.dev/docs/ci
This snippet shows the fundamental steps for running Playwright tests on an Azure Pipelines agent. It includes Node.js installation, dependency installation, Playwright browser installation, and test execution.
```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'
```
--------------------------------
### Setup: Create GitHub Repository
Source: https://playwright.dev/docs/api-testing
Use a beforeAll hook to create a new repository via the GitHub API before running tests. Assumes REPO and USER are defined.
```typescript
test.beforeAll(async ({ request }) => {
const response = await request.post('/user/repos', {
data: {
name: REPO
}
});
expect(response.ok()).toBeTruthy();
});
```
--------------------------------
### startTime
Source: https://playwright.dev/docs/api/class-teststep
Gets the start time of this particular test step as a Date object.
```APIDOC
## startTime
### Description
Start time of this particular test step.
### Usage
`testStep.startTime`
### Type
* Date
```
--------------------------------
### Get Browser Name
Source: https://playwright.dev/docs/api/class-browsertype
Retrieves the name of the browser type. For example, 'chromium', 'webkit', or 'firefox'.
```javascript
browserType.name();
```
--------------------------------
### Update Component with Playwright
Source: https://playwright.dev/docs/testing-library
Example of getting the update function after mounting a component with Playwright Component Testing.
```javascript
const { update } = await mount();
```
--------------------------------
### open
Source: https://playwright.dev/docs/api/class-androiddevice
Launches a process in the device's shell and returns a socket for communication.
```APIDOC
## open
### Description
Launches a process in the shell on the device and returns a socket to communicate with the launched process.
### Method
`await androidDevice.open(command)
### Parameters
#### Arguments
* `command` string - Shell command to execute.
### Returns
* Promise
```
--------------------------------
### Rerender Component with Testing Library
Source: https://playwright.dev/docs/testing-library
Example of getting the rerender function after rendering a component with Testing Library.
```javascript
const { rerender } = render();
```
--------------------------------
### Initialize Playwright Project
Source: https://playwright.dev
Use this command to set up a new Playwright project. It installs the latest version of Playwright and configures the necessary files.
```bash
npm init playwright@latest
```
--------------------------------
### List Reporter Example Output
Source: https://playwright.dev/docs/test-reporters
This shows an example of the List reporter's output in the middle of a test run. Failures are typically listed at the end.
```text
npx playwright test --reporter=list
Running 124 tests using 6 workers
1 ✓ should access error in env (438ms)
2 ✓ handle long test names (515ms)
3 x 1) render expected (691ms)
4 ✓ should timeout (932ms)
5 should repeat each:
6 ✓ should respect enclosing .gitignore (569ms)
7 should teardown env after timeout:
8 should respect excluded tests:
9 ✓ should handle env beforeEach error (638ms)
10 should respect enclosing .gitignore:
```
--------------------------------
### Unmount Component with Playwright
Source: https://playwright.dev/docs/testing-library
Example of getting the unmount function after mounting a component with Playwright Component Testing.
```javascript
const { unmount } = await mount();
```
--------------------------------
### Registering and Installing a Passkey
Source: https://playwright.dev/docs/release-notes
This snippet demonstrates how to use the `browserContext.credentials` API to register a passkey for a test user and install it for use with `navigator.credentials.create()` and `navigator.credentials.get()` ceremonies. Ensure you have the necessary credential details like `credentialId`, `userHandle`, `privateKey`, and `publicKey`.
```javascript
const context = await browser.newContext();
// Seed a passkey your backend provisioned for a test user.
await context.credentials.create('example.com', {
id: credentialId,
userHandle,
privateKey,
publicKey,
});
await context.credentials.install();
const page = await context.newPage();
await page.goto('https://example.com/login');
// The page's navigator.credentials.get() is answered with the seeded passkey.
```
--------------------------------
### Unmount Component with Testing Library
Source: https://playwright.dev/docs/testing-library
Example of getting the unmount function after rendering a component with Testing Library.
```javascript
const { unmount } = render();
```
--------------------------------
### Accessing testInfo.titlePath
Source: https://playwright.dev/docs/api/class-testinfo
Example of accessing the full title path of the current test, starting with the test file name.
```javascript
testInfo.titlePath
```
--------------------------------
### Launch Browser and Create Context with Proxy
Source: https://playwright.dev/docs/network
Launch a browser and then create a new context with a specific proxy. This demonstrates setting up a proxy for a particular browsing session.
```typescript
const browser = await chromium.launch();
const context = await browser.newContext({
proxy: { server: 'http://myproxy.com:3128' }
});
```
--------------------------------
### Record with Custom Browser Context Setup
Source: https://playwright.dev/docs/codegen
Use `page.pause()` to start codegen recording within a custom browser context. Ensure the browser is launched in headed mode. This is useful for non-standard setups like intercepting network requests.
```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();
})();
```
--------------------------------
### Install Clock and Fast Forward Timers
Source: https://playwright.dev/docs/clock
Install the clock with an initial time and use `pauseAt` and `fastForward` to simulate time progression. This is ideal for testing timers that depend on `Date.now`.
```html
```
```javascript
// Initialize clock with some time before the test time and let the page load
// naturally. `Date.now` will progress as the timers fire.
await page.clock.install({ time: new Date('2024-02-02T08:00:00') });
await page.goto('http://localhost:3333');
// Pretend that the user closed the laptop lid and opened it again at 10am,
// Pause the time once reached that point.
await page.clock.pauseAt(new Date('2024-02-02T10:00:00'));
// Assert the page state.
await expect(page.getByTestId('current-time')).toHaveText('2/2/2024, 10:00:00 AM');
// Close the laptop lid again and open it at 10:30am.
await page.clock.fastForward('30:00');
await expect(page.getByTestId('current-time')).toHaveText('2/2/2024, 10:30:00 AM');
```
--------------------------------
### Access Worker Index
Source: https://playwright.dev/docs/api/class-testresult
Get the index of the worker where the test was executed. A value of -1 indicates the test was not run, for example, due to an interruption.
```javascript
testResult.workerIndex
```
--------------------------------
### credentials.install
Source: https://playwright.dev/docs/api/class-credentials
Installs the virtual WebAuthn authenticator into the context, overriding navigator.credentials.create() and navigator.credentials.get() in all current and future pages.
```APIDOC
## credentials.install
### Description
Installs the virtual WebAuthn authenticator into the context, overriding `navigator.credentials.create()` and `navigator.credentials.get()` in all current and future pages. Call this before the page first touches `navigator.credentials`. Required: until credentials.install() is called, no interception is in place and the page sees the platform's native (or absent) WebAuthn behaviour.
### Method
credentials.install
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
await credentials.install();
```
### Response
#### Success Response (200)
None (void)
#### Response Example
None
```
--------------------------------
### Execute code before all tests
Source: https://playwright.dev/docs/api/class-test
Use `test.beforeAll` to declare a hook that runs once before all tests in a file or describe block. This example logs a message indicating the start of tests.
```typescript
import { test, expect } from '@playwright/test';
test.beforeAll(async () => {
console.log('Before tests');
});
test.afterAll(async () => {
console.log('After tests');
});
test('my test', async ({ page }) => {
// ...
});
```
--------------------------------
### Create and Navigate a Page
Source: https://playwright.dev/docs/pages
Demonstrates creating a new page, navigating to a URL, filling an input field, clicking a link, and logging the current URL.
```javascript
const page = await context.newPage();
await page.goto('http://example.com');
await page.locator('#search').fill('query');
await page.locator('#submit').click();
console.log(page.url());
```
--------------------------------
### Puppeteer Test Example with Jest
Source: https://playwright.dev/docs/puppeteer
A test case using Puppeteer with Jest to verify the hero title on the Playwright homepage. Includes setup and teardown for the browser instance.
```javascript
import puppeteer from 'puppeteer';
describe('Playwright homepage', () => {
let browser;
let page;
beforeAll(async () => {
browser = await puppeteer.launch();
page = await browser.newPage();
});
it('contains hero title', async () => {
await page.goto('https://playwright.dev/');
await page.waitForSelector('.hero__title');
const text = await page.$eval('.hero__title', e => e.textContent);
expect(text).toContain('Playwright enables reliable end-to-end testing'); // 5
});
afterAll(() => browser.close());
});
```
--------------------------------
### Run Setup Before Each Test
Source: https://playwright.dev/docs/best-practices
Use `beforeEach` hooks to perform common setup tasks like navigating to a URL and logging in before each test runs. This ensures tests are isolated and reproducible.
```typescript
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.
});
```
--------------------------------
### Configure Project Teardown in Playwright
Source: https://playwright.dev/docs/release-notes
Specify a teardown project to run after dependent projects complete, useful for resource cleanup. This example demonstrates setting up a 'setup' project with a 'teardown' dependency.
```typescript
import { defineConfig } from '@playwright/test';
export default defineConfig({
projects: [
{
name: 'setup',
testMatch: /global.setup\.ts/,
teardown: 'teardown',
},
{
name: 'teardown',
testMatch: /global.teardown\.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'],
},
],
});
```
--------------------------------
### Register and Capture Passkey in Setup
Source: https://playwright.dev/docs/auth
This snippet is used in a setup project to register a new passkey with the application and then capture it for later use. It saves the captured credential to a JSON file.
```typescript
import { test as setup } from '@playwright/test';
import fs from 'fs';
setup('enroll passkey', async ({ context, page }) => {
await context.credentials.install();
await page.goto('https://example.com/register');
// The app calls navigator.credentials.create() to register the passkey.
await page.getByRole('button', { name: 'Create a passkey' }).click();
// Read back the registered passkey, including its private key, and save it.
const [credential] = await context.credentials.get({ rpId: 'example.com' });
fs.writeFileSync('playwright/.auth/passkey.json', JSON.stringify(credential));
});
```
--------------------------------
### Agentic Video Receipt Example
Source: https://playwright.dev/docs/release-notes
Generate a video receipt with annotations for agentic work. This includes starting screencast, showing actions and chapters, performing task steps, and stopping the recording.
```typescript
await page.screencast.start({ path: 'receipt.webm' });
await page.screencast.showActions({ position: 'top-right' });
await page.screencast.showChapter('Verifying checkout flow', {
description: 'Added coupon code support per ticket #1234',
});
// Agent performs the verification steps...
await page.locator('#coupon').fill('SAVE20');
await page.locator('#apply-coupon').click();
await expect(page.locator('.discount')).toContainText('20%');
await page.screencast.showChapter('Done', {
description: 'Coupon applied, discount reflected in total',
});
await page.screencast.stop();
```
--------------------------------
### Playwright Library Example (JavaScript)
Source: https://playwright.dev/docs/library
Launches a browser, navigates to a page, and asserts its title using the Playwright library directly. Requires explicit setup and teardown of browser contexts and pages.
```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();
})();
```
--------------------------------
### Playwright Library Example (TypeScript)
Source: https://playwright.dev/docs/library
Launches a browser, navigates to a page, and asserts its title using the Playwright library directly. Requires explicit setup and teardown of browser contexts and pages.
```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();
})();
```
--------------------------------
### testInfo.workerIndex
Source: https://playwright.dev/docs/api/class-testinfo
The unique index of the worker process that is running the test. When a worker is restarted, for example after a failure, the new worker process gets a new unique `workerIndex`. Also available as `process.env.TEST_WORKER_INDEX`.
```APIDOC
## testInfo.workerIndex
### Description
The unique index of the worker process that is running the test. When a worker is restarted, for example after a failure, the new worker process gets a new unique `workerIndex`.
Also available as `process.env.TEST_WORKER_INDEX`. Learn more about parallelism and sharding with Playwright Test.
### Usage
```
testInfo.workerIndex
```
### Type
* number
```
--------------------------------
### WebStorage Basic Operations
Source: https://playwright.dev/docs/api/class-webstorage
Demonstrates common WebStorage operations including setting, getting, retrieving all items, removing, and clearing storage.
```javascript
await page.goto('https://example.com');
await page.localStorage.setItem('token', 'abc');
const token = await page.localStorage.getItem('token');
const all = await page.localStorage.items();
await page.localStorage.removeItem('token');
await page.localStorage.clear();
```
--------------------------------
### Define Fixtures and Options in JavaScript
Source: https://playwright.dev/docs/api/class-test
This JavaScript snippet shows how to extend the base test object to define a 'defaultItem' option and a 'todoPage' fixture. It mirrors the TypeScript example, providing setup and teardown for the fixture.
```javascript
const base = require('@playwright/test');
const { TodoPage } = require('./todo-page');
// Extend basic test by providing a "defaultItem" option and a "todoPage" fixture.
exports.test = base.test.extend({
// Define an option and provide a default value.
// We can later override it in the config.
defaultItem: ['Do stuff', { option: true }],
// Define a fixture. Note that it can use built-in fixture "page"
// and a new option "defaultItem".
todoPage: async ({ page, defaultItem }, use) => {
const todoPage = new TodoPage(page);
await todoPage.goto();
await todoPage.addToDo(defaultItem);
await use(todoPage);
await todoPage.removeAll();
},
});
```
--------------------------------
### Configure Global Setup
Source: https://playwright.dev/docs/api/class-testconfig
Specify the path to a global setup file that runs before all tests. This file must export a single function accepting a FullConfig argument. Multiple paths can be provided as an array.
```typescript
import { defineConfig } from '@playwright/test';
export default defineConfig({
globalSetup: './global-setup',
});
```
--------------------------------
### Get List of Detected Android Devices
Source: https://playwright.dev/docs/api/class-android
Retrieve a list of all Android devices currently detected by Playwright. Optional arguments allow specifying the ADB host, port, and whether to omit driver installation.
```typescript
await android.devices();
await android.devices(options);
```
--------------------------------
### Getting the Path of a Downloaded File
Source: https://playwright.dev/docs/api/class-download
Returns the local file system path of a successfully downloaded file. This method waits for the download to complete. It throws an error for failed or canceled downloads. Note that the actual filename is a GUID; use `suggestedFilename()` for a user-friendly name.
```javascript
await download.path();
```
--------------------------------
### Install Playwright Browsers
Source: https://playwright.dev/docs/library
Download and install the necessary browser binaries for Playwright. Alternatively, add browser-specific packages to automatically install browsers on npm install.
```bash
# Download the Chromium, Firefox and WebKit browser
npx playwright install chromium firefox webkit
```
```bash
# Alternatively, add packages that will download a browser upon npm install
npm i -D @playwright/browser-chromium @playwright/browser-firefox @playwright/browser-webkit
```
--------------------------------
### Full Page Interaction Example
Source: https://playwright.dev/docs/api/class-fixtures
A comprehensive example of using the 'page' fixture to navigate to a sign-in page, fill in credentials, and click the sign-in button. This highlights common end-to-end testing actions.
```typescript
import { test, expect } from '@playwright/test';
test('basic test', async ({ page }) => {
await page.goto('/signin');
await page.getByLabel('User Name').fill('user');
await page.getByLabel('Password').fill('password');
await page.getByText('Sign in').click();
// ...
});
```
--------------------------------
### Launch Browser Server and Connect
Source: https://playwright.dev/docs/api/class-browsertype
Launches a browser server and then connects to it using the WebSocket endpoint. This is useful for managing browser instances externally.
```javascript
const { chromium } = require('playwright'); // Or 'webkit' or 'firefox'.
(async () => {
const browserServer = await chromium.launchServer();
const wsEndpoint = browserServer.wsEndpoint();
// Use web socket endpoint later to establish a connection.
const browser = await chromium.connect(wsEndpoint);
// Close browser instance.
await browserServer.close();
})();
```
--------------------------------
### Using Test Hooks for Test Grouping and Setup
Source: https://playwright.dev/docs/writing-tests
Illustrates the use of `test.describe` to group tests and `test.beforeEach` to set up common preconditions before each test within the group. The `page.goto()` command navigates to a specific URL.
```typescript
import { test, expect } from '@playwright/test';
test.describe('navigation', () => {
test.beforeEach(async ({ page }) => {
// Go to the starting url before each test.
await page.goto('https://playwright.dev/');
});
test('main navigation', async ({ page }) => {
// Assertions use the expect API.
await expect(page).toHaveURL('https://playwright.dev/');
});
});
```
--------------------------------
### Create Page, Navigate, and Screenshot
Source: https://playwright.dev/docs/api/class-page
This snippet demonstrates the basic workflow of launching a browser, creating a new page, navigating to a URL, and capturing a screenshot.
```javascript
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
(async () => {
const browser = await webkit.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.com');
await page.screenshot({ path: 'screenshot.png' });
await browser.close();
})();
```
--------------------------------
### Install Playwright CLI Locally with npx
Source: https://playwright.dev/docs/getting-started-cli
Install the playwright-cli package as a local dependency and execute it using npx. This is useful for project-specific installations.
```bash
npx playwright-cli --help
```
--------------------------------
### Install APK on Android Device
Source: https://playwright.dev/docs/api/class-androiddevice
Installs an APK file onto the Android device. Allows passing custom arguments to the installation command.
```typescript
await androidDevice.installApk(file);
await androidDevice.installApk(file, options);
```
--------------------------------
### screencast.start
Source: https://playwright.dev/docs/api/class-screencast
Starts the screencast. Can be used to record video to a file or deliver JPEG-encoded frames to a callback.
```APIDOC
## start screencast.start
### Description
Starts the screencast. When path is provided, it saves video recording to the specified file. When onFrame is provided, delivers JPEG-encoded frames to the callback. Both can be used together.
### Method
Not applicable (SDK method)
### Parameters
#### Optional Arguments
- **options** (Object)
- **onFrame** (function(Object):Promise) _(optional)_
- **data** (Buffer) - JPEG-encoded frame data.
- **timestamp** (number) - The timestamp of when the frame was presented by the browser, in milliseconds since the Unix epoch.
- **viewportWidth** (number) - Width of the page viewport at the time the frame was captured.
- **viewportHeight** (number) - Height of the page viewport at the time the frame was captured.
Callback that receives JPEG-encoded frame data along with the page viewport size at the time of capture.
- **path** (string) _(optional)_ - Path where the video should be saved when the screencast is stopped. When provided, video recording is started.
- **quality** (number) _(optional)_ - The quality of the image, between 0-100.
- **size** (Object) _(optional)_
- **width** (number) - Max frame width in pixels.
- **height** (number) - Max frame height in pixels.
Specifies the dimensions of screencast frames. The actual frame is scaled to preserve the page's aspect ratio and may be smaller than these bounds. If a screencast is already active (e.g. started by tracing or video recording), the existing configuration takes precedence and the frame size may exceed these bounds or this option may be ignored. If not specified the size will be equal to page viewport scaled down to fit into 800×800.
### Returns
- **Promise**
```
--------------------------------
### Install Playwright Browser via npm Package
Source: https://playwright.dev/docs/library
Install a Playwright browser package (e.g., `@playwright/browser-chromium`) to automatically download the respective browser during package installation.
```bash
# Use a helper package that downloads a browser on npm install
npm install @playwright/browser-chromium
```
--------------------------------
### Hermetic Install to Local Folder (PowerShell)
Source: https://playwright.dev/docs/browsers
Configure PLAYWRIGHT_BROWSERS_PATH to '0' in PowerShell to install browser binaries into the local node_modules\playwright-core\.local-browsers directory, facilitating hermetic installations.
```powershell
# Places binaries to node_modules\playwright-core\.local-browsers
$Env:PLAYWRIGHT_BROWSERS_PATH=0
npx playwright install
```
--------------------------------
### Example Planner Output: Basic Operations Test Plan
Source: https://playwright.dev/docs/test-agents
This is an example Markdown test plan generated by the planner agent for the TodoMVC application. It outlines the application overview and detailed test scenarios.
```markdown
# TodoMVC Application - Basic Operations Test Plan
## Application Overview
The TodoMVC application is a React-based todo list manager that demonstrates standard todo application functionality. The application provides comprehensive task management capabilities with a clean, intuitive interface. Key features include:
- **Task Management**: Add, edit, complete, and delete individual todos
- **Bulk Operations**: Mark all todos as complete/incomplete and clear all completed todos
- **Filtering System**: View todos by All, Active, or Completed status with URL routing support
- **Real-time Counter**: Display of active (incomplete) todo count
- **Interactive UI**: Hover states, edit-in-place functionality, and responsive design
- **State Persistence**: Maintains state during session navigation
## Test Scenarios
### 1. Adding New Todos
**Seed:** `tests/seed.spec.ts`
#### 1.1 Add Valid Todo
**Steps:**
1. Click in the "What needs to be done?" input field
2. Type "Buy groceries"
3. Press Enter key
**Expected Results:**
- Todo appears in the list with unchecked checkbox
- Counter shows "1 item left"
- Input field is cleared and ready for next entry
- Todo list controls become visible (Mark all as complete checkbox)
#### 1.2 Add Multiple Todos
...
```
--------------------------------
### Configure Browser Launch Options
Source: https://playwright.dev/docs/test-use-options
Pass options directly to `browserType.launch()` via the `launchOptions` in the `use` section. This example sets `slowMo` to 50ms.
```typescript
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
launchOptions: {
slowMo: 50,
},
},
});
```
--------------------------------
### Hermetic Install to Local Folder (Batch)
Source: https://playwright.dev/docs/browsers
Set PLAYWRIGHT_BROWSERS_PATH to '0' in a batch script to install browser binaries into the local node_modules\playwright-core\.local-browsers folder, enabling hermetic installations.
```batch
# Places binaries to node_modules\playwright-core\.local-browsers
set PLAYWRIGHT_BROWSERS_PATH=0
npx playwright install
```
--------------------------------
### Listen for Page Load Event
Source: https://playwright.dev/docs/api/class-page
This example shows how to use the `once` method to log a message when the page's `load` event fires.
```javascript
page.once('load', () => console.log('Page loaded!'));
```
--------------------------------
### Install Chromium Headless Shell Only
Source: https://playwright.dev/docs/browsers
For CI environments or when only running tests headlessly, install only the headless shell to save disk space. Use the `--only-shell` flag during installation.
```bash
# only running tests headlessly
npx playwright install --with-deps --only-shell
```
--------------------------------
### Configure Browser Launch Options
Source: https://playwright.dev/docs/api/class-testoptions
Provide custom arguments for launching the browser. This allows for advanced configurations like maximizing the window.
```typescript
import { defineConfig } from '@playwright/test';
export default defineConfig({
projects: [
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
launchOptions: {
args: ['--start-maximized']
}
}
}
]
});
```
--------------------------------
### Install Browsers via HTTPS Proxy (Batch)
Source: https://playwright.dev/docs/browsers
Use this command to install Playwright browsers when behind an HTTPS proxy. Set the HTTPS_PROXY environment variable before running the install command.
```batch
set HTTPS_PROXY=https://192.0.2.1
npx playwright install
```
--------------------------------
### Install Browsers via HTTPS Proxy (PowerShell)
Source: https://playwright.dev/docs/browsers
Use this command to install Playwright browsers when behind an HTTPS proxy. Set the HTTPS_PROXY environment variable before running the install command.
```powershell
$Env:HTTPS_PROXY="https://192.0.2.1"
npx playwright install
```
--------------------------------
### Configuring Web Server Launch for Tests
Source: https://playwright.dev/docs/release-notes
Launch a web server before tests run using the `webServer` option in the configuration file. The server waits for a specified URL to be available.
```typescript
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: {
command: 'npm run start',
url: 'http://127.0.0.1:3000',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
});
```
--------------------------------
### Install Browsers via HTTPS Proxy (Bash)
Source: https://playwright.dev/docs/browsers
Use this command to install Playwright browsers when behind an HTTPS proxy. Set the HTTPS_PROXY environment variable before running the install command.
```bash
HTTPS_PROXY=https://192.0.2.1 npx playwright install
```
--------------------------------
### Start Selenium Hub Docker Container
Source: https://playwright.dev/docs/selenium-grid
Initiate a Selenium Hub using the official Docker image. Expose the necessary ports for communication between the hub, nodes, and clients.
```bash
docker run -d -p 4442-4444:4442-4444 --name selenium-hub selenium/hub:4.25.0
```
--------------------------------
### Access Start Time
Source: https://playwright.dev/docs/api/class-testresult
Retrieve the start time of this particular test run.
```javascript
testResult.startTime
```
--------------------------------
### Accessing use Property
Source: https://playwright.dev/docs/api/class-testproject
Demonstrates how to access the use property of a project.
```javascript
testProject.use
```
--------------------------------
### Install Playwright Test
Source: https://playwright.dev/docs/release-notes
Use this command to install Playwright Test as a development dependency.
```bash
npm i -D @playwright/test
```
--------------------------------
### BrowserType.launch
Source: https://playwright.dev/docs/api/class-browsertype
Launches a new browser instance with specified options. This method allows for extensive configuration, including custom arguments, proxy settings, and headless mode.
```APIDOC
## BrowserType.launch
### Description
Launches a new browser instance with specified options. This method allows for extensive configuration, including custom arguments, proxy settings, and headless mode.
### Method
launch(options?: BrowserTypeLaunchOptions)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* `options` (Object) - Optional configuration for the browser instance.
* `args` (Array) - Optional. Additional arguments to pass to the browser instance.
* `artifactsDir` (string) - Optional. Directory to save artifacts like traces, videos, etc.
* `channel` (string) - Optional. Browser distribution channel (e.g., "chromium", "chrome").
* `chromiumSandbox` (boolean) - Optional. Enable Chromium sandboxing. Defaults to `false`.
* `downloadsPath` (string) - Optional. Directory for downloaded files.
* `env` (Object) - Optional. Environment variables for the browser process.
* `executablePath` (string) - Optional. Path to a custom browser executable.
* `firefoxUserPrefs` (Object) - Optional. Firefox user preferences.
* `handleSIGHUP` (boolean) - Optional. Close the browser process on SIGHUP. Defaults to `true`.
* `handleSIGINT` (boolean) - Optional. Close the browser process on Ctrl-C. Defaults to `true`.
* `handleSIGTERM` (boolean) - Optional. Close the browser process on SIGTERM. Defaults to `true`.
* `headless` (boolean) - Optional. Whether to run in headless mode. Defaults to `true`.
* `host` (string) - Optional. Host to use for the web socket. Defaults to `localhost`.
* `ignoreDefaultArgs` (boolean | Array) - Optional. Whether to ignore default browser arguments.
* `logger` (Logger) - Optional. Logger sink for Playwright logging (Deprecated).
* `port` (number) - Optional. Port to use for the web socket. Defaults to 0 (picks any available port).
* `proxy` (Object) - Optional. Network proxy settings.
* `server` (string) - Proxy server address (e.g., "http://myproxy.com:3128").
* `bypass` (string) - Optional. Comma-separated domains to bypass proxy.
* `username` (string) - Optional. Username for proxy authentication.
* `password` (string) - Optional. Password for proxy authentication.
* `timeout` (number) - Optional. Maximum time in milliseconds to wait for the browser to start. Defaults to 30000.
* `tracesDir` (string) - Optional. Directory to save traces.
* `wsPath` (string) - Optional. Path at which to serve the Browser Server.
### Request Example
```json
{
"options": {
"headless": false,
"args": ["--no-sandbox"]
}
}
```
### Response
#### Success Response (200)
* `Promise` - A promise that resolves to a BrowserServer instance.
#### Response Example
```json
{
"browserServer": ""
}
```
```