### Full Tracing Workflow Example Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-tracing.md This example demonstrates the complete process of starting a trace, performing browser actions like navigation, and then stopping the trace to save it to a file. It captures screenshots and snapshots. ```js const browser = await chromium.launch(); const context = await browser.newContext(); await context.tracing.start({ screenshots: true, snapshots: true }); const page = await context.newPage(); await page.goto('https://playwright.dev'); expect(page.url()).toBe('https://playwright.dev'); await context.tracing.stop({ path: 'trace.zip' }); ``` ```java Browser browser = chromium.launch(); BrowserContext context = browser.newContext(); context.tracing().start(new Tracing.StartOptions() .setScreenshots(true) .setSnapshots(true)); Page page = context.newPage(); page.navigate("https://playwright.dev"); context.tracing().stop(new Tracing.StopOptions() .setPath(Paths.get("trace.zip"))); ``` ```python async browser = await chromium.launch() context = await browser.new_context() await context.tracing.start(screenshots=True, snapshots=True) page = await context.new_page() await page.goto("https://playwright.dev") await context.tracing.stop(path = "trace.zip") ``` ```python sync browser = chromium.launch() context = browser.new_context() context.tracing.start(screenshots=True, snapshots=True) page = context.new_page() page.goto("https://playwright.dev") context.tracing.stop(path = "trace.zip") ``` ```csharp using var playwright = await Playwright.CreateAsync(); var browser = await playwright.Chromium.LaunchAsync(); await using var context = await browser.NewContextAsync(); await context.Tracing.StartAsync(new() { Screenshots = true, Snapshots = true }); var page = await context.NewPageAsync(); await page.GotoAsync("https://playwright.dev"); await context.Tracing.StopAsync(new() { Path = "trace.zip" }); ``` -------------------------------- ### Install Browser and System Dependencies Together (CLI) Source: https://github.com/microsoft/playwright/blob/main/docs/src/browsers.md Combines browser installation with system dependency installation for a specified browser, like Chromium, into a single command. This streamlines setup for new environments. ```bash npx playwright install --with-deps chromium ``` ```bash mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps chromium" ``` ```bash playwright install --with-deps chromium ``` ```bash pwsh bin/Debug/netX/playwright.ps1 install --with-deps chromium ``` -------------------------------- ### Complete GitHub API Test Example in C# Source: https://github.com/microsoft/playwright/blob/main/docs/src/api-testing-csharp.md This comprehensive example demonstrates setting up API request contexts, creating and deleting test repositories, and performing POST and GET requests to manage issues, with assertions for response status and content. ```csharp using System.Text.Json; using Microsoft.Playwright; using Microsoft.Playwright.MSTest; namespace PlaywrightTests; [TestClass] public class TestGitHubAPI : PlaywrightTest { static string REPO = "test-repo-2"; static string USER = Environment.GetEnvironmentVariable("GITHUB_USER"); static string? API_TOKEN = Environment.GetEnvironmentVariable("GITHUB_API_TOKEN"); private IAPIRequestContext Request = null!; [TestMethod] public async Task ShouldCreateBugReport() { var data = new Dictionary { { "title", "[Bug] report 1" }, { "body", "Bug description" } }; var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data }); await Expect(newIssue).ToBeOKAsync(); var issues = await Request.GetAsync("/repos/" + USER + "/" + REPO + "/issues"); await Expect(newIssue).ToBeOKAsync(); var issuesJsonResponse = await issues.JsonAsync(); JsonElement? issue = null; foreach (JsonElement issueObj in issuesJsonResponse?.EnumerateArray()) { if (issueObj.TryGetProperty("title", out var title) == true) { if (title.GetString() == "[Bug] report 1") { issue = issueObj; } } } Assert.IsNotNull(issue); Assert.AreEqual("Bug description", issue?.GetProperty("body").GetString()); } [TestMethod] public async Task ShouldCreateFeatureRequests() { var data = new Dictionary { { "title", "[Feature] request 1" }, { "body", "Feature description" } }; var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data }); await Expect(newIssue).ToBeOKAsync(); var issues = await Request.GetAsync("/repos/" + USER + "/" + REPO + "/issues"); await Expect(newIssue).ToBeOKAsync(); var issuesJsonResponse = await issues.JsonAsync(); JsonElement? issue = null; foreach (JsonElement issueObj in issuesJsonResponse?.EnumerateArray()) { if (issueObj.TryGetProperty("title", out var title) == true) { if (title.GetString() == "[Feature] request 1") { issue = issueObj; } } } Assert.IsNotNull(issue); Assert.AreEqual("Feature description", issue?.GetProperty("body").GetString()); } [TestInitialize] public async Task SetUpAPITesting() { await CreateAPIRequestContext(); await CreateTestRepository(); } private async Task CreateAPIRequestContext() { var headers = new Dictionary { // We set this header per GitHub guidelines. { "Accept", "application/vnd.github.v3+json" }, // Add authorization token to all requests. // Assuming personal access token available in the environment. { "Authorization", "token " + API_TOKEN } }; Request = await Playwright.APIRequest.NewContextAsync(new() { // All requests we send go to this API endpoint. BaseURL = "https://api.github.com", ExtraHTTPHeaders = headers, }); } private async Task CreateTestRepository() { var resp = await Request.PostAsync("/user/repos", new() { DataObject = new Dictionary() { ["name"] = REPO, }, }); await Expect(resp).ToBeOKAsync(); } [TestCleanup] public async Task TearDownAPITesting() { await DeleteTestRepository(); await Request.DisposeAsync(); } private async Task DeleteTestRepository() { var resp = await Request.DeleteAsync("/repos/" + USER + "/" + REPO); await Expect(resp).ToBeOKAsync(); } } ``` -------------------------------- ### Global Setup with Trace Capture for Failures Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-global-setup-teardown-js.md This global setup captures a trace if an error occurs during the setup process. It starts tracing, performs setup actions, and stops tracing with different paths for success or failure. ```js 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; } } export default globalSetup; ``` -------------------------------- ### Install Dependencies and Build Playwright Source: https://github.com/microsoft/playwright/blob/main/CONTRIBUTING.md Install project dependencies, start the build process in watch mode, and install Playwright browser binaries. ```bash npm ci npm run watch npx playwright install ``` -------------------------------- ### Implementing tests with `TodoPage` using `beforeEach` and `afterEach` Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-fixtures-js.md This example shows a traditional test setup using `beforeEach` and `afterEach` hooks to manage the `TodoPage` instance and clean up items, contrasting with a fixture-based approach. ```js 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'); // ... }); }); ``` -------------------------------- ### Initialize New Playwright Project Source: https://github.com/microsoft/playwright/blob/main/FILING_ISSUES.md Start a new Playwright project with the latest version to create a clean, minimal reproducible example for bug reporting. ```shell npm init playwright@latest new-project ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/microsoft/playwright/blob/main/tests/components/ct-vue-vite/README.md Use this command to install all required project dependencies. ```sh npm install ``` -------------------------------- ### Install Playwright Test CLI Source: https://github.com/microsoft/playwright/blob/main/README.md Initialize a new Playwright project and install Playwright Test using the CLI. ```bash npm init playwright@latest ``` -------------------------------- ### Install Playwright with uv Source: https://github.com/microsoft/playwright/blob/main/docs/src/library-python.md Use these commands to install Playwright and its browser binaries using uv. ```bash uv self update uv add playwright playwright install ``` -------------------------------- ### Launch Browser and Navigate to URL (Multiple Languages) Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-browsertype.md This example demonstrates how to launch a browser instance, create a new page, navigate to a specified URL, and then close the browser using Playwright. It covers common setup and teardown for browser automation. ```javascript const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'. (async () => { const browser = await chromium.launch(); const page = await browser.newPage(); await page.goto('https://example.com'); // other actions... await browser.close(); })(); ``` ```java import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType chromium = playwright.chromium(); Browser browser = chromium.launch(); Page page = browser.newPage(); page.navigate("https://example.com"); // other actions... browser.close(); } } } ``` ```python async import asyncio from playwright.async_api import async_playwright, Playwright async def run(playwright: Playwright): chromium = playwright.chromium browser = await chromium.launch() page = await browser.new_page() await page.goto("https://example.com") # other actions... await browser.close() async def main(): async with async_playwright() as playwright: await run(playwright) asyncio.run(main()) ``` ```python sync from playwright.sync_api import sync_playwright, Playwright def run(playwright: Playwright): chromium = playwright.chromium browser = chromium.launch() page = browser.new_page() page.goto("https://example.com") # other actions... browser.close() with sync_playwright() as playwright: run(playwright) ``` ```csharp using Microsoft.Playwright; using System.Threading.Tasks; class BrowserTypeExamples { public static async Task Run() { using var playwright = await Playwright.CreateAsync(); var chromium = playwright.Chromium; var browser = await chromium.LaunchAsync(); var page = await browser.NewPageAsync(); await page.GotoAsync("https://www.bing.com"); // other actions await browser.CloseAsync(); } } ``` -------------------------------- ### Using Descriptive Filenames for Playwright CLI Video Recordings Source: https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/video-recording.md Examples of how to start video recording with Playwright CLI using descriptive filenames to include context like dates or test run identifiers. ```bash # Include context in filename playwright-cli video-start recordings/login-flow-2024-01-15.webm playwright-cli video-start recordings/checkout-test-run-42.webm ``` -------------------------------- ### Create Vue Component Test File (Script Setup) Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-components-js.md Example of a basic Playwright component test for a Vue application, mounting an App component and asserting its text content. ```js import { test, expect } from '@playwright/experimental-ct-vue'; import App from './App.vue'; test('should work', async ({ mount }) => { const component = await mount(App); await expect(component).toContainText('Learn Vue'); }); ``` -------------------------------- ### Install playwright-cli globally Source: https://github.com/microsoft/playwright/blob/main/docs/src/getting-started-cli.md Install the Playwright CLI tool globally to make it accessible from any directory, then verify the installation by displaying help. ```bash npm install -g @playwright/cli@latest playwright-cli --help ``` -------------------------------- ### Accessing Web Storage with Page.localStorage and Page.sessionStorage Source: https://github.com/microsoft/playwright/blob/main/docs/src/release-notes-js.md This example illustrates how to use the new `WebStorage` API to read and write items in a page's local and session storage. It shows setting and getting an item from `localStorage` and retrieving all items from `sessionStorage`. ```js await page.localStorage.setItem('token', 'abc'); const token = await page.localStorage.getItem('token'); const items = await page.sessionStorage.items(); ``` -------------------------------- ### Install Azure CLI Source: https://github.com/microsoft/playwright/blob/main/utils/flakiness-dashboard/README.md Updates Homebrew and installs the Azure Command Line Interface. ```bash brew update && brew install azure-cli ``` -------------------------------- ### Define project dependencies for global setup Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-api/class-testproject.md Use this configuration to define project dependencies, ensuring a 'setup' project runs before other browser-specific projects. This is useful for managing global setup actions and producing artifacts. ```js import { defineConfig } from '@playwright/test'; export default defineConfig({ projects: [ { name: 'setup', testMatch: /global.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 Playwright with Poetry Source: https://github.com/microsoft/playwright/blob/main/docs/src/library-python.md Use these commands to install Playwright and its browser binaries using Poetry. ```bash poetry self update poetry add playwright playwright install ``` -------------------------------- ### Example Playwright Test Depending on Global Setup Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-global-setup-teardown-js.md An example Playwright test (`menu.spec.ts`) that will run after the global setup project has completed, ensuring any necessary resources (like a database) are ready. ```typescript import { test, expect } from '@playwright/test'; test('menu', async ({ page }) => { // Your test that depends on the database }); ``` -------------------------------- ### Launch Browser, Create Page, Navigate, and Close Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-browser.md Demonstrates how to launch a browser, create a new page, navigate to a URL, and then close the browser instance. This is a fundamental flow for browser automation. ```javascript const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'. (async () => { const browser = await firefox.launch(); const page = await browser.newPage(); await page.goto('https://example.com'); await browser.close(); })(); ``` ```java import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType firefox = playwright.firefox(); Browser browser = firefox.launch(); Page page = browser.newPage(); page.navigate("https://example.com"); browser.close(); } } } ``` ```python async import asyncio from playwright.async_api import async_playwright, Playwright async def run(playwright: Playwright): firefox = playwright.firefox browser = await firefox.launch() page = await browser.new_page() await page.goto("https://example.com") await browser.close() async def main(): async with async_playwright() as playwright: await run(playwright) asyncio.run(main()) ``` ```python sync from playwright.sync_api import sync_playwright, Playwright def run(playwright: Playwright): firefox = playwright.firefox browser = firefox.launch() page = browser.new_page() page.goto("https://example.com") browser.close() with sync_playwright() as playwright: run(playwright) ``` ```csharp using Microsoft.Playwright; using var playwright = await Playwright.CreateAsync(); var firefox = playwright.Firefox; var browser = await firefox.LaunchAsync(new() { Headless = false }); var page = await browser.NewPageAsync(); await page.GotoAsync("https://www.bing.com"); await browser.CloseAsync(); ``` -------------------------------- ### Line Reporter Example Output Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-reporters-js.md This example shows the output of the Line reporter during a test run, including an inline failure report. ```bash npx playwright test --reporter=line Running 124 tests using 6 workers 1) dot-reporter.spec.ts:20:1 › render expected =================================================== Error: expect(received).toBe(expected) // Object.is equality Expected: 1 Received: 0 [23/124] gitignore.spec.ts - should respect nested .gitignore ``` -------------------------------- ### Initialize and Pause Clock with install and pauseAt Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-clock.md Use `install` to set an initial time and allow timers to fire naturally, then `pauseAt` to halt time at a specific point during page load or test execution. ```javascript await page.clock.install(time=datetime.datetime(2024, 12, 10, 8, 0, 0)) await page.goto("http://localhost:3333") await page.clock.pause_at(datetime.datetime(2024, 12, 10, 10, 0, 0)) ``` ```python sync page.clock.install(time=datetime.datetime(2024, 12, 10, 8, 0, 0)) page.goto("http://localhost:3333") page.clock.pause_at(datetime.datetime(2024, 12, 10, 10, 0, 0)) ``` ```java SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd'T'HH:mm:ss"); page.clock().install(new Clock.InstallOptions().setTime(format.parse("2024-12-10T08:00:00"))); page.navigate("http://localhost:3333"); page.clock().pauseAt(format.parse("2024-12-10T10:00:00")); ``` -------------------------------- ### Install Playwright Browsers Source: https://github.com/microsoft/playwright/blob/main/docs/src/intro-python.md Run this command to download and install the necessary browser binaries (Chromium, Firefox, WebKit) for Playwright to function. ```bash playwright install ``` -------------------------------- ### Set up Playwright .NET Console Project Source: https://github.com/microsoft/playwright/blob/main/docs/src/library-csharp.md Initializes a new .NET console application, adds the Playwright NuGet package, builds the project, and installs necessary browser drivers. Ensure PowerShell is updated if the `pwsh` command throws TypeNotFound. ```bash # Create project dotnet new console -n PlaywrightDemo cd PlaywrightDemo # Add project dependency dotnet add package Microsoft.Playwright # Build the project dotnet build # Install required browsers - replace netX with actual output folder name, e.g. net8.0. pwsh bin/Debug/netX/playwright.ps1 install # If the pwsh command does not work (throws TypeNotFound), make sure to use an up-to-date version of PowerShell. dotnet tool update --global PowerShell ``` -------------------------------- ### Perform Setup and Teardown with beforeAll and afterAll Hooks (JavaScript) Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-api/class-test.md Execute setup logic once before all tests in a worker process using `beforeAll` and corresponding teardown with `afterAll`. ```javascript 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 }) => { // ... }); ``` -------------------------------- ### End-to-End Electron App Automation Example Source: https://github.com/microsoft/playwright/blob/main/docs/src/electron-api/class-electron.md This comprehensive example demonstrates launching an Electron app, evaluating code in its main process, interacting with its first window, taking a screenshot, and handling console output. ```js 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(); })(); ``` -------------------------------- ### Get Response End Time in C# Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-request.md Example of using `page.RunAndWaitForRequestFinishedAsync` to capture a request and then access its `Timing.ResponseEnd` property. ```csharp var request = await page.RunAndWaitForRequestFinishedAsync(async () => { await page.GotoAsync("https://www.microsoft.com"); }); Console.WriteLine(request.Timing.ResponseEnd); ``` -------------------------------- ### Complete GitHub API Test Example in Java Source: https://github.com/microsoft/playwright/blob/main/docs/src/api-testing-java.md This comprehensive example demonstrates setting up Playwright's APIRequestContext for GitHub, creating and deleting repositories, and testing issue creation with POST and GET requests, including JSON parsing and assertions. ```java package org.example; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.microsoft.playwright.APIRequest; import com.microsoft.playwright.APIRequestContext; import com.microsoft.playwright.APIResponse; import com.microsoft.playwright.Playwright; import com.microsoft.playwright.options.RequestOptions; import org.junit.jupiter.api.*; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.junit.jupiter.api.Assertions.*; @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestGitHubAPI { private static final String REPO = "test-repo-2"; private static final String USER = System.getenv("GITHUB_USER"); private static final String API_TOKEN = System.getenv("GITHUB_API_TOKEN"); private Playwright playwright; private APIRequestContext request; void createPlaywright() { playwright = Playwright.create(); } void createAPIRequestContext() { Map headers = new HashMap<>(); // We set this header per GitHub guidelines. headers.put("Accept", "application/vnd.github.v3+json"); // Add authorization token to all requests. // Assuming personal access token available in the environment. headers.put("Authorization", "token " + API_TOKEN); request = playwright.request().newContext(new APIRequest.NewContextOptions() // All requests we send go to this API endpoint. .setBaseURL("https://api.github.com") .setExtraHTTPHeaders(headers)); } void createTestRepository() { APIResponse newRepo = request.post("/user/repos", RequestOptions.create().setData(Collections.singletonMap("name", REPO))); assertTrue(newRepo.ok(), newRepo.text()); } @BeforeAll void beforeAll() { createPlaywright(); createAPIRequestContext(); createTestRepository(); } void deleteTestRepository() { if (request != null) { APIResponse deletedRepo = request.delete("/repos/" + USER + "/" + REPO); assertTrue(deletedRepo.ok()); } } void disposeAPIRequestContext() { if (request != null) { request.dispose(); request = null; } } void closePlaywright() { if (playwright != null) { playwright.close(); playwright = null; } } @AfterAll void afterAll() { deleteTestRepository(); disposeAPIRequestContext(); closePlaywright(); } @Test void shouldCreateBugReport() { Map data = new HashMap<>(); data.put("title", "[Bug] report 1"); data.put("body", "Bug description"); APIResponse newIssue = request.post("/repos/" + USER + "/" + REPO + "/issues", RequestOptions.create().setData(data)); assertTrue(newIssue.ok()); APIResponse issues = request.get("/repos/" + USER + "/" + REPO + "/issues"); assertTrue(issues.ok()); JsonArray json = new Gson().fromJson(issues.text(), JsonArray.class); JsonObject issue = null; for (JsonElement item : json) { JsonObject itemObj = item.getAsJsonObject(); if (!itemObj.has("title")) { continue; } if ("[Bug] report 1".equals(itemObj.get("title").getAsString())) { issue = itemObj; break; } } assertNotNull(issue); assertEquals("Bug description", issue.get("body").getAsString(), issue.toString()); } @Test void shouldCreateFeatureRequest() { Map data = new HashMap<>(); data.put("title", "[Feature] request 1"); data.put("body", "Feature description"); APIResponse newIssue = request.post("/repos/" + USER + "/" + REPO + "/issues", RequestOptions.create().setData(data)); assertTrue(newIssue.ok()); APIResponse issues = request.get("/repos/" + USER + "/" + REPO + "/issues"); assertTrue(issues.ok()); JsonArray json = new Gson().fromJson(issues.text(), JsonArray.class); JsonObject issue = null; for (JsonElement item : json) { JsonObject itemObj = item.getAsJsonObject(); if (!itemObj.has("title")) { continue; } if ("[Feature] request 1".equals(itemObj.get("title").getAsString())) { issue = itemObj; break; } } assertNotNull(issue); assertEquals("Feature description", issue.get("body").getAsString(), issue.toString()); } } ``` -------------------------------- ### Seed and Install WebAuthn Passkey in Playwright C# Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-credentials.md This snippet demonstrates how to seed a captured passkey into a new browser context and install the virtual WebAuthn authenticator. This allows the application to start with an already enrolled passkey, enabling navigator.credentials.get() to resolve it. ```csharp // later test: seed the captured passkey so the app starts already enrolled. var credential = JsonSerializer.Deserialize( File.ReadAllText("playwright/.auth/passkey.json")); var context = await browser.NewContextAsync(); await context.Credentials.CreateAsync(credential.RpId, new() { Id = credential.Id, UserHandle = credential.UserHandle, PrivateKey = credential.PrivateKey, PublicKey = credential.PublicKey, }); await context.Credentials.InstallAsync(); var page = await context.NewPageAsync(); await page.GotoAsync("https://example.com/login"); // navigator.credentials.get() resolves the captured passkey — already signed in. ``` -------------------------------- ### async method: Electron.launch Source: https://github.com/microsoft/playwright/blob/main/docs/src/electron-api/class-electron.md Launches an Electron application with specified configurations. This method returns an `ElectronApplication` instance, which can then be used to interact with the launched app. ```APIDOC ## async method: Electron.launch ### Description Launches electron application specified with the `executablePath` option. ### Method launch ### Parameters #### Request Body - **executablePath** (string) - Optional - Launches given Electron application. If not specified, launches the default Electron executable installed in this package, located at `node_modules/.bin/electron`. - **args** (Array) - Optional - Additional arguments to pass to the application when launching. You typically pass the main script name here. - **cwd** (string) - Optional - Current working directory to launch application from. - **env** (Object) - Optional - Specifies environment variables that will be visible to Electron. Defaults to `process.env`. - **timeout** (float) - Optional - Maximum time in milliseconds to wait for the application to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. ### Response #### Success Response (200) - **ElectronApplication** (object) - An instance representing the launched Electron application. ``` -------------------------------- ### HTML Setup for Multi-Select Element Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-locatorassertions.md This HTML defines a multi-select dropdown element with several options, used as a target for the `toHaveValues` assertion examples. ```html ``` -------------------------------- ### Launch Browser Server and Connect (JavaScript) Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-browsertype.md This snippet demonstrates how to launch a browser server, retrieve its WebSocket endpoint, and then connect to it using `BrowserType.connect`. Remember to close the `browserServer` instance when done. ```js 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(); })(); ``` -------------------------------- ### GitHub Actions Workflow for Playwright Tests (Python) Source: https://github.com/microsoft/playwright/blob/main/docs/src/ci.md Configures a GitHub Actions workflow to run Playwright tests for Python projects on push and pull request events, including Python setup, dependency installation, Playwright browser installation, and pytest execution. ```yml 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 - name: Set up Python uses: actions/setup-python@v6 with: python-version: '3.13' - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Ensure browsers are installed run: python -m playwright install --with-deps - name: Run your tests run: pytest --tracing=retain-on-failure - uses: actions/upload-artifact@v5 if: ${{ !cancelled() }} with: name: playwright-traces path: test-results/ ``` -------------------------------- ### View Playwright project file structure Source: https://github.com/microsoft/playwright/blob/main/docs/src/intro-js.md This shows the default file structure created after installing Playwright, including configuration and example test files. ```bash playwright.config.ts # Test configuration package.json package-lock.json # Or yarn.lock / pnpm-lock.yaml tests/ example.spec.ts # Minimal example test ``` -------------------------------- ### async method: Disposable.dispose Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-disposable.md Removes the associated resource that the Disposable instance represents. For example, it can remove an init script previously installed on a Page or BrowserContext. ```APIDOC ## Disposable.dispose ### Description Removes the associated resource. For example, removes the init script installed via [`method: Page.addInitScript`] or [`method: BrowserContext.addInitScript`]. ### Signature async dispose(): Promise ### Parameters This method does not take any explicit parameters. ### Example ```javascript const disposable = await page.addInitScript(() => console.log('init script')); // ... later in your test or application ... await disposable.dispose(); // Removes the init script ``` ### Returns `Promise` - A promise that resolves when the associated resource has been successfully removed. ``` -------------------------------- ### Run Development Server (npm) Source: https://github.com/microsoft/playwright/blob/main/tests/components/ct-vue-cli/README.md Starts the development server, compiling and hot-reloading the application for local development. ```bash npm run serve ``` -------------------------------- ### Get Request Timing in JavaScript Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-request.md Use `request.timing()` to retrieve performance metrics for a finished network request. This example logs the full timing object. ```js const requestFinishedPromise = page.waitForEvent('requestfinished'); await page.goto('http://example.com'); const request = await requestFinishedPromise; console.log(request.timing()); ``` -------------------------------- ### Playwright Test Using Pre-authenticated State Source: https://github.com/microsoft/playwright/blob/main/docs/src/test-global-setup-teardown-js.md This test demonstrates how tests automatically start authenticated when `storageState` is configured in `playwright.config.ts` and populated by a global setup. ```js import { test } from '@playwright/test'; test('test', async ({ page }) => { await page.goto('/'); // You are signed in! }); ``` -------------------------------- ### Initialize a New Playwright Project Source: https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/test-generation.md Run this command to bootstrap a new Playwright project, allowing the user to select default configurations. ```bash npm init playwright@latest ``` -------------------------------- ### Tracing.start Method Usage Example Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-tracing.md This snippet demonstrates how to use `context.tracing.start` to initiate trace collection with screenshot and snapshot options, followed by page navigation and stopping the trace. This is a common pattern for debugging. ```js await context.tracing.start({ screenshots: true, snapshots: true }); const page = await context.newPage(); await page.goto('https://playwright.dev'); expect(page.url()).toBe('https://playwright.dev'); await context.tracing.stop({ path: 'trace.zip' }); ``` ```java context.tracing().start(new Tracing.StartOptions() .setScreenshots(true) .setSnapshots(true)); Page page = context.newPage(); page.navigate("https://playwright.dev"); context.tracing().stop(new Tracing.StopOptions() .setPath(Paths.get("trace.zip"))); ``` ```python async await context.tracing.start(screenshots=True, snapshots=True) page = await context.new_page() await page.goto("https://playwright.dev") await context.tracing.stop(path = "trace.zip") ``` ```python sync context.tracing.start(screenshots=True, snapshots=True) page = context.new_page() page.goto("https://playwright.dev") context.tracing.stop(path = "trace.zip") ``` ```csharp using var playwright = await Playwright.CreateAsync(); var browser = await playwright.Chromium.LaunchAsync(); await using var context = await browser.NewContextAsync(); await context.Tracing.StartAsync(new() { Screenshots = true, Snapshots = true }); var page = await context.NewPageAsync(); await page.GotoAsync("https://playwright.dev"); await context.Tracing.StopAsync(new() { Path = "trace.zip" }); ``` -------------------------------- ### Create a Git Branch for Playwright Development Source: https://github.com/microsoft/playwright/blob/main/CLAUDE.md Example of creating a new Git branch, typically for a bug fix or new feature, before starting development work. ```bash git checkout -b fix-39562 ``` -------------------------------- ### Manipulate Time with Playwright Java Clock API Source: https://github.com/microsoft/playwright/blob/main/docs/src/release-notes-java.md This example demonstrates how to install, pause, and fast-forward the clock to control time-related behavior in tests, useful for verifying time-dependent features. ```java // Initialize clock with some time before the test time and let the page load // naturally. `Date.now` will progress as the timers fire. page.clock().install(new Clock.InstallOptions().setTime("2024-02-02T08:00:00")); page.navigate("http://localhost:3333"); Locator locator = page.getByTestId("current-time"); // Pretend that the user closed the laptop lid and opened it again at 10am. // Pause the time once reached that point. page.clock().pauseAt("2024-02-02T10:00:00"); // Assert the page state. assertThat(locator).hasText("2/2/2024, 10:00:00 AM"); // Close the laptop lid again and open it at 10:30am. page.clock().fastForward("30:00"); assertThat(locator).hasText("2/2/2024, 10:30:00 AM"); ``` -------------------------------- ### Credentials.install() Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-credentials.md Installs the virtual WebAuthn authenticator into the BrowserContext, enabling it to intercept and respond to `navigator.credentials.create()` and `navigator.credentials.get()` calls within the page. ```APIDOC ## Credentials.install() ### Description Installs the virtual WebAuthn authenticator into the BrowserContext, enabling it to intercept and respond to `navigator.credentials.create()` and `navigator.credentials.get()` calls within the page. This method must be called before the page attempts to use WebAuthn credentials. ### Method Signature `async context.credentials.install()` ### Parameters None. ``` ```javascript const context = await browser.newContext(); await context.credentials.install(); // Now the context is ready to handle WebAuthn operations. ``` ```java BrowserContext context = browser.newContext(); context.credentials().install(); // Now the context is ready to handle WebAuthn operations. ``` ```python async context = await browser.new_context() await context.credentials.install() # Now the context is ready to handle WebAuthn operations. ``` ```python sync context = browser.new_context() context.credentials.install() # Now the context is ready to handle WebAuthn operations. ``` ```csharp var context = await browser.NewContextAsync(); await context.Credentials.InstallAsync(); // Now the context is ready to handle WebAuthn operations. ``` -------------------------------- ### Manage Test Repository with Setup/Teardown Hooks (C#) Source: https://github.com/microsoft/playwright/blob/main/docs/src/api-testing-csharp.md This snippet illustrates using [TestInitialize] and [TestCleanup] hooks to set up and tear down test environments. It creates a temporary GitHub repository before tests and deletes it after. ```csharp using System.Text.Json; using Microsoft.Playwright; using Microsoft.Playwright.MSTest; namespace PlaywrightTests; [TestClass] public class TestGitHubAPI : PlaywrightTest { // ... [TestInitialize] public async Task SetUpAPITesting() { await CreateAPIRequestContext(); await CreateTestRepository(); } private async Task CreateTestRepository() { var resp = await Request.PostAsync("/user/repos", new() { DataObject = new Dictionary() { ["name"] = REPO, }, }); await Expect(resp).ToBeOKAsync(); } [TestCleanup] public async Task TearDownAPITesting() { await DeleteTestRepository(); await Request.DisposeAsync(); } private async Task DeleteTestRepository() { var resp = await Request.DeleteAsync("/repos/" + USER + "/" + REPO); await Expect(resp).ToBeOKAsync(); } } ``` -------------------------------- ### Using Function-Scoped Pytest Fixtures for Setup and Teardown Source: https://github.com/microsoft/playwright/blob/main/docs/src/writing-tests-python.md This example shows how to define an `autouse` `function`-scoped Pytest fixture to run code before and after each test, such as navigating to a specific URL or performing other setup/teardown actions. ```python import pytest from playwright.sync_api import Page, expect @pytest.fixture(scope="function", autouse=True) def before_each_after_each(page: Page): print("before the test runs") # Go to the starting url before each test. page.goto("https://playwright.dev/") yield print("after the test runs") def test_main_navigation(page: Page): # Assertions use the expect API. expect(page).to_have_url("https://playwright.dev/") ``` -------------------------------- ### Record Video with Screencast.start (JavaScript) Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-screencast.md Use this snippet to start recording a video of the page to a specified file path. Remember to call `screencast.stop()` to save the video. ```js await page.screencast.start({ path: 'video.webm', size: { width: 1280, height: 800 } }); // ... perform actions ... await page.screencast.stop(); ``` -------------------------------- ### Implement Seed Test with Custom Fixture for Navigation Source: https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/test-generation.md Define a custom Playwright fixture to handle common setup like navigation, then use it in the seed test to ensure all scenarios start from a consistent state. ```ts // tests/fixtures.ts import { test as baseTest } from '@playwright/test'; export { expect } from '@playwright/test'; export const test = baseTest.extend({ page: async ({ page }, use) => { await page.goto('https://example.com/'); await use(page); }, }); ``` ```ts // tests/seed.spec.ts import { test } from './fixtures'; test('seed', async ({ page }) => { // Fixture already navigates. This empty body tells agents where to start. }); ``` -------------------------------- ### Screencast.start Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-screencast.md 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. ```APIDOC ## async method: 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. ### Parameters #### Options - **onFrame** (function(Object)): Optional - Callback that receives JPEG-encoded frame data along with the page viewport size at the time of capture. - **data** (Buffer) - JPEG-encoded frame data. - **timestamp** (float) - The timestamp of when the frame was presented by the browser, in milliseconds since the Unix epoch. - **viewportWidth** (int) - Width of the page viewport at the time the frame was captured. - **viewportHeight** (int) - Height of the page viewport at the time the frame was captured. - **path** (path): Optional - Path where the video should be saved when the screencast is stopped. When provided, video recording is started. - **quality** (int): Optional - The quality of the image, between 0-100. - **size** (Object): Optional - 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 not specified the size will be equal to page viewport scaled down to fit into 800x800. - **width** (int) - Max frame width in pixels. - **height** (int) - Max frame height in pixels. ### Returns ``` -------------------------------- ### async method: Tracing.start Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-tracing.md Start tracing. This method initiates the collection of browser operations and network activity. It can be configured to include screenshots and snapshots. ```APIDOC ## async method: Tracing.start ### Description Start tracing. This method initiates the collection of browser operations and network activity. It can be configured to include screenshots and snapshots. ### Method `start` ### Usage `context.tracing.start(options)` ### Parameters #### Options - **screenshots** (boolean) - Optional - Whether to capture screenshots during tracing. - **snapshots** (boolean) - Optional - Whether to capture DOM snapshots during tracing. - **name** (string) - Optional - If specified, intermediate trace files are going to be saved into files with the given name prefix inside the `tracesDir` directory. To specify the final trace zip file name, use the `path` option in `Tracing.stop`. ### Request Example ```json { "screenshots": true, "snapshots": true, "name": "my-session-trace" } ``` ``` -------------------------------- ### Asserting API Response is OK in a Test Context Source: https://github.com/microsoft/playwright/blob/main/docs/src/api/class-apiresponseassertions.md These examples demonstrate how to assert that an API response's status code is within the 200-299 range, indicating a successful operation, within a full test setup. ```js import { test, expect } from '@playwright/test'; test('navigates to login', async ({ page }) => { // ... const response = await page.request.get('https://playwright.dev'); await expect(response).toBeOK(); }); ``` ```java // ... import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; public class TestPage { // ... @Test void navigatesToLoginPage() { // ... APIResponse response = page.request().get("https://playwright.dev"); assertThat(response).isOK(); } } ``` ```python async from playwright.async_api import Page, expect async def test_navigates_to_login_page(page: Page) -> None: # .. response = await page.request.get('https://playwright.dev') await expect(response).to_be_ok() ``` ```python sync from playwright.sync_api import Page, expect def test_navigates_to_login_page(page: Page) -> None: # .. response = page.request.get('https://playwright.dev') expect(response).to_be_ok() ``` ```csharp using Microsoft.Playwright; using Microsoft.Playwright.MSTest; namespace PlaywrightTests; [TestClass] public class ExampleTests : PageTest { [TestMethod] public async Task NavigatesToLoginPage() { var response = await Page.APIRequest.GetAsync("https://playwright.dev"); await Expect(response).ToBeOKAsync(); } } ``` -------------------------------- ### Playwright Authentication Setup File Source: https://github.com/microsoft/playwright/blob/main/docs/src/auth.md This setup file performs the authentication steps, navigates to the login page, fills credentials, and saves the authenticated browser state to a file for reuse. ```js import { test as setup, expect } from '@playwright/test'; import path from 'path'; const authFile = path.join(__dirname, '../playwright/.auth/user.json'); setup('authenticate', async ({ page }) => { // Perform authentication steps. Replace these actions with your own. 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(); // Wait until the page receives the cookies. // // Sometimes login flow sets cookies in the process of several redirects. // Wait for the final URL to ensure that the cookies are actually set. await page.waitForURL('https://github.com/'); // Alternatively, you can wait until the page reaches a state where all cookies are set. await expect(page.getByRole('button', { name: 'View profile and more' })).toBeVisible(); // End of authentication steps. await page.context().storageState({ path: authFile }); }); ```