### Install Dependencies and Start Development Server Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/tests/components/ct-svelte/README.md Install project dependencies using npm and start the development server to see your app running locally. ```bash cd svelte-app npm install ``` ```bash npm run dev ``` -------------------------------- ### Install Clock and Pause at Specific Time (Python Sync) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/api/class-clock.md Synchronous Python example for installing the clock with a starting time, navigating, and then pausing at a specific point. This method helps manage timer behavior during page load. ```python # 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(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)) ``` -------------------------------- ### Example Global Setup for Authentication Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/test-global-setup-teardown-js.md A global setup script that authenticates a user and saves the storage state for reuse in tests. It requires baseURL and storageState to be configured. ```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(); } ``` -------------------------------- ### Full Example Test in Java Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/writing-tests-java.md A complete example demonstrating test setup, navigation, assertions on title and attributes, and clicking a link. ```java package org.example; import java.util.regex.Pattern; import com.microsoft.playwright.*; import com.microsoft.playwright.options.AriaRole; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; public class App { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { Browser browser = playwright.chromium().launch(); Page page = browser.newPage(); page.navigate("https://playwright.dev"); // Expect a title "to contain" a substring. assertThat(page).hasTitle(Pattern.compile("Playwright")); // create a locator Locator getStarted = page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName("Get Started")); // Expect an attribute "to be strictly equal" to the value. assertThat(getStarted).hasAttribute("href", "/docs/intro"); // Click the get started link. getStarted.click(); // Expects page to have a heading with the name of Installation. assertThat(page.getByRole(AriaRole.HEADING, new Page.GetByRoleOptions().setName("Installation"))).isVisible(); } } } ``` -------------------------------- ### Install Clock and Pause at Specific Time (Java) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/api/class-clock.md Java example demonstrating how to install the clock with an initial time, navigate to a page, and then pause at a specific time. This is a best practice for ensuring timers function correctly during page loading. ```java # Initialize clock with some time before the test time and let the page load # naturally. `Date.now` will progress as the timers fire. 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 Clock and Pause at Specific Time (JavaScript) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/api/class-clock.md This example demonstrates installing the clock with an initial time before navigation, then pausing at a specific time. This ensures timers behave normally during page load. ```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-12-10T08:00:00') }); await page.goto('http://localhost:3333'); await page.clock.pauseAt(new Date('2024-12-10T10:00:00')); ``` -------------------------------- ### Install Clock and Pause at Specific Time (Python Async) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/api/class-clock.md Asynchronous Python example showing clock installation with an initial time, followed by navigation and pausing at a target time. This approach is recommended for consistent timer behavior during page loading. ```python # 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=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)) ``` -------------------------------- ### Record with custom setup in JavaScript Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/codegen.md Launch a browser in headed mode and set up a custom context with routing before pausing to start manual recording. ```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 Dependencies and Build Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/CONTRIBUTING.md Install project dependencies using npm ci and start the build process in watch mode. Also, install Playwright browser binaries. ```bash npm ci npm run watch npx playwright install ``` -------------------------------- ### Capture Trace on Global Setup Failure Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/test-global-setup-teardown-js.md An enhanced global setup script that captures a trace of failures using try...catch, starting 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; } } ``` -------------------------------- ### Define Setup Project Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/test-global-setup-teardown-js.md Define a project to run global setup tasks. Use `testMatch` to specify the setup file. ```javascript import { defineConfig } from '@playwright/test'; export default defineConfig({ testDir: './tests', // ... projects: [ { name: 'setup db', testMatch: /global\.setup\.ts/, }, // { // other project // } ] }); ``` -------------------------------- ### Basic WebGL Rendering Setup and Drawing Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/tests/assets/screenshots/webgl.html Initializes WebGL context, sets clear color, compiles shaders, sets up vertex attributes, and draws a triangle strip. This is a minimal example for rendering. ```javascript var gl = document.getElementById("webgl") .getContext("experimental-webgl"); gl.clearColor(0.8, 0.8, 0.8, 1); gl.clear(gl.COLOR_BUFFER_BIT); var prog = shaderProgram(gl, "attribute vec3 pos;\nvoid main(){\n gl_Position = vec4(pos, 2.0);\n}", "void main(){\n gl_FragColor = vec4(0.5, 0.5, 1.0, 1.0);\n}" ); gl.useProgram(prog); attributeSetFloats(gl, prog, "pos", 3, [ -1, 0, 0, 0, 1, 0, 0, -1, 0, 1, 0, 0 ]); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); ``` -------------------------------- ### Launching a Browser Instance Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/api/class-browsertype.md This example demonstrates how to launch a new browser instance using the BrowserType. The 'launch' method starts a browser process, and the returned Browser object can be used to create new pages. ```APIDOC ## launch ### Description Launches a new browser instance. ### Method `launch()` ### Parameters This method does not take any parameters in this context. ### Response #### Success Response - **browser** (Browser) - A Browser instance. ### Request Example ```javascript const browser = await chromium.launch(); ``` ### Response Example ```javascript // browser is a Browser instance ``` ``` -------------------------------- ### Run Setup Before Each Test in Playwright Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/best-practices-js.md Use `test.beforeEach` to execute setup logic, like logging in, before each test in a file. This ensures each test starts from a consistent state. ```javascript import { test } from '@playwright/test'; test.beforeEach(async ({ page }) => { // Runs before each test and signs in each page. await page.goto('https://github.com/login'); await page.getByLabel('Username or email address').fill('username'); await page.getByLabel('Password').fill('password'); await page.getByRole('button', { name: 'Sign in' }).click(); }); test('first', async ({ page }) => { // page is signed in. }); test('second', async ({ page }) => { // page is signed in. }); ``` -------------------------------- ### TestNG Example with Playwright Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/test-runners-java.md This example shows how to initialize Playwright and Browser in @BeforeClass and destroy them in @AfterClass. Each test method gets its own BrowserContext and Page. ```java package org.example; import com.microsoft.playwright.Browser; import com.microsoft.playwright.BrowserContext; import com.microsoft.playwright.Page; import com.microsoft.playwright.Playwright; import org.testng.annotations.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class TestExample { // Shared between all tests in this class. Playwright playwright; Browser browser; // New instance for each test method. BrowserContext context; Page page; @BeforeClass void launchBrowser() { playwright = Playwright.create(); browser = playwright.chromium().launch(); } @AfterClass void closeBrowser() { playwright.close(); } @BeforeMethod void createContextAndPage() { context = browser.newContext(); page = context.newPage(); } @AfterMethod void closeContext() { context.close(); } @Test void shouldClickButton() { page.navigate("data:text/html,"); page.locator("button").click(); assertEquals("Clicked", page.evaluate("result")); } @Test void shouldCheckTheBox() { page.setContent(""); page.locator("input").check(); assertTrue((Boolean) page.evaluate("() => window['checkbox'].checked")); } @Test void shouldSearchWiki() { page.navigate("https://www.wikipedia.org/"); page.locator("input[name=\"search\"]").click(); page.locator("input[name=\"search\"]").fill("playwright"); page.locator("input[name=\"search\"]").press("Enter"); assertEquals("https://en.wikipedia.org/wiki/Playwright", page.url()); } } ``` -------------------------------- ### Global Setup Test Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/test-global-setup-teardown-js.md Create a setup test file to perform initialization tasks. This file should be matched by the `testMatch` property of the setup project. ```typescript import { test as setup } from '@playwright/test'; setup('create new database', async ({ }) => { console.log('creating new database...'); // Initialize the database }); ``` -------------------------------- ### Start waiting for download before clicking Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/api/class-page.md This example shows how to initiate a wait for a 'download' event before performing an action that triggers it. The download promise is created first, then the click action is performed, and finally, the download is awaited. ```js const downloadPromise = page.waitForEvent('download'); await page.getByText('Download file').click(); const download = await downloadPromise; ``` -------------------------------- ### Install Browsers with Per-Browser Host (PowerShell) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/browsers.md Configure specific download hosts for individual browsers and a general download host using PowerShell environment variables. This example is for PowerShell. ```js $Env:PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST="http://203.0.113.3" $Env:PLAYWRIGHT_DOWNLOAD_HOST="http://192.0.2.1" npx playwright install ``` ```python $Env:PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST="http://203.0.113.3" $Env:PLAYWRIGHT_DOWNLOAD_HOST="http://192.0.2.1" pip install playwright playwright install ``` ```java $Env:PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST="http://203.0.113.3" $Env:PLAYWRIGHT_DOWNLOAD_HOST="http://192.0.2.1" mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install" ``` ```csharp $Env:PLAYWRIGHT_DOWNLOAD_HOST="http://192.0.2.1" $Env:PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST="http://203.0.113.3" pwsh bin/Debug/netX/playwright.ps1 install ``` -------------------------------- ### Install .NET SDK 9.0 Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/docker.md Installs a specific .NET channel using the official install script. Ensure the target directory is appropriate for your environment. ```bash curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin --install-dir /usr/share/dotnet --channel 9.0 ``` -------------------------------- ### Install Browsers with Per-Browser Host (Batch) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/browsers.md Set environment variables for specific browser download hosts (e.g., Firefox) and a general download host using a batch script. This example is for Windows command prompt. ```js set PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST=http://203.0.113.3 set PLAYWRIGHT_DOWNLOAD_HOST=http://192.0.2.1 npx playwright install ``` ```python set PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST=http://203.0.113.3 set PLAYWRIGHT_DOWNLOAD_HOST=http://192.0.2.1 pip install playwright playwright install ``` ```java set PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST=http://203.0.113.3 set PLAYWRIGHT_DOWNLOAD_HOST=http://192.0.2.1 mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install" ``` ```csharp set PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST=http://203.0.113.3 set PLAYWRIGHT_DOWNLOAD_HOST=http://192.0.2.1 pwsh bin/Debug/netX/playwright.ps1 install ``` -------------------------------- ### React Component Test Setup Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/test-components-js.md Example of setting up a component test for a React application using @playwright/experimental-ct-react. Includes viewport configuration. ```javascript import { test, expect } from '@playwright/experimental-ct-react'; import HelloWorld from './HelloWorld'; test.use({ viewport: { width: 500, height: 500 } }); test('should work', async ({ mount }) => { const component = await mount(); await expect(component).toContainText('Greetings'); }); ``` -------------------------------- ### Configure Global Setup File Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/test-api/class-testconfig.md Specifies the path to a global setup file that runs before all tests. This file must export a function to perform setup tasks. Multiple setup files can be specified as an array. ```typescript import { defineConfig } from '@playwright/test'; export default defineConfig({ globalSetup: './global-setup', }); ``` -------------------------------- ### Install agent-base with npm Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/packages/playwright-core/ThirdPartyNotices.txt Install the agent-base module using npm. ```bash npm install agent-base ``` -------------------------------- ### MSTest Example Test Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/intro-csharp.md This snippet demonstrates end-to-end testing with Playwright and MSTest. It includes tests for checking the page title and interacting with a 'Get started' link. ```csharp using System.Text.RegularExpressions; using Microsoft.Playwright; using Microsoft.Playwright.MSTest; namespace PlaywrightTests; [TestClass] public class ExampleTest : PageTest { [TestMethod] public async Task HasTitle() { await Page.GotoAsync("https://playwright.dev"); // Expect a title "to contain" a substring. await Expect(Page).ToHaveTitleAsync(new Regex("Playwright")); } [TestMethod] public async Task GetStartedLink() { await Page.GotoAsync("https://playwright.dev"); // Click the get started link. await Page.GetByRole(AriaRole.Link, new() { Name = "Get started" }).ClickAsync(); // Expects page to have a heading with the name of Installation. await Expect(Page.GetByRole(AriaRole.Heading, new() { Name = "Installation" })).ToBeVisibleAsync(); } } ``` -------------------------------- ### Example Playwright Pytest Test Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/intro-python.md This Python code defines two example tests using Playwright and Pytest. The first test checks the page title, and the second test verifies the visibility of the 'Get started' heading after clicking a link. ```python import re from playwright.sync_api import Page, expect def test_has_title(page: Page): page.goto("https://playwright.dev/") # Expect a title "to contain" a substring. expect(page).to_have_title(re.compile("Playwright")) def test_get_started_link(page: Page): page.goto("https://playwright.dev/") # Click the get started link. page.get_by_role("link", name="Get started").click() # Expects page to have a heading with the name of Installation. expect(page.get_by_role("heading", name="Installation")).to_be_visible() ``` -------------------------------- ### xUnit Example Test Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/intro-csharp.md This snippet illustrates how to implement end-to-end tests using Playwright with xUnit. It covers tests for verifying the page title and clicking a 'Get started' link. ```csharp using System.Text.RegularExpressions; using Microsoft.Playwright; using Microsoft.Playwright.Xunit; namespace PlaywrightTests; public class UnitTest1: PageTest { [Fact] public async Task HasTitle() { await Page.GotoAsync("https://playwright.dev"); // Expect a title "to contain" a substring. await Expect(Page).ToHaveTitleAsync(new Regex("Playwright")); } [Fact] public async Task GetStartedLink() { await Page.GotoAsync("https://playwright.dev"); // Click the get started link. await Page.GetByRole(AriaRole.Link, new() { Name = "Get started" }).ClickAsync(); // Expects page to have a heading with the name of Installation. await Expect(Page.GetByRole(AriaRole.Heading, new() { Name = "Installation" })).ToBeVisibleAsync(); } } ``` -------------------------------- ### NUnit Example Test Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/intro-csharp.md This snippet shows how to write end-to-end tests using Playwright with NUnit. It includes tests for verifying the page title and clicking a 'Get started' link. ```csharp using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.Playwright; using Microsoft.Playwright.NUnit; using NUnit.Framework; namespace PlaywrightTests; [Parallelizable(ParallelScope.Self)] [TestFixture] public class ExampleTest : PageTest { [Test] public async Task HasTitle() { await Page.GotoAsync("https://playwright.dev"); // Expect a title "to contain" a substring. await Expect(Page).ToHaveTitleAsync(new Regex("Playwright")); } [Test] public async Task GetStartedLink() { await Page.GotoAsync("https://playwright.dev"); // Click the get started link. await Page.GetByRole(AriaRole.Link, new() { Name = "Get started" }).ClickAsync(); // Expects page to have a heading with the name of Installation. await Expect(Page.GetByRole(AriaRole.Heading, new() { Name = "Installation" })).ToBeVisibleAsync(); } } ``` -------------------------------- ### Declare a beforeEach hook Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/test-api/class-test.md Use test.beforeEach to run code before each test. Access fixtures like 'page' and use test.info() to get test details. This example navigates to a starting URL. ```javascript import { test, expect } from '@playwright/test'; test.beforeEach(async ({ page }) => { console.log(`Running ${test.info().title}`); await page.goto('https://my.start.url/'); }); test('my test', async ({ page }) => { expect(page.url()).toBe('https://my.start.url/'); }); ``` -------------------------------- ### Record with custom setup in Python (async) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/codegen.md Use the async API to launch Chromium, set up a custom context with routing, and then pause the page for manual recording. ```python import asyncio from playwright.async_api import async_playwright async def main(): async with async_playwright() as p: # Make sure to run headed. browser = await p.chromium.launch(headless=False) # Setup context however you like. context = await browser.new_context() # Pass any options await context.route('**/*', lambda route: route.continue_()) # Pause the page, and start recording manually. page = await context.new_page() await page.pause() asyncio.run(main()) ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/tests/components/ct-vue-cli/README.md Installs all necessary packages for the project. Run this after cloning the repository. ```bash npm install ``` -------------------------------- ### Install Browsers in CI Configuration Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/release-notes-js.md Example of how to install Playwright browsers with dependencies in a CI environment after a clean npm install. ```yaml run: npm ci run: npx playwright install --with-deps ``` -------------------------------- ### Setup: Create Repository Before Tests Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/api-testing-js.md Use the `beforeAll` hook to create a new repository via API before any tests in the suite run. Asserts that the repository creation request was successful. ```javascript test.beforeAll(async ({ request }) => { // Create a new repository const response = await request.post('/user/repos', { data: { name: REPO } }); expect(response.ok()).toBeTruthy(); }); ``` -------------------------------- ### List Installed Browsers (Java) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/browsers.md Use Maven to execute the Playwright CLI command to list all installed browsers across all installations on the machine. ```bash mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --list" ``` -------------------------------- ### Install socks-proxy-agent Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/packages/playwright-core/ThirdPartyNotices.txt Install the socks-proxy-agent package using npm. ```bash npm install socks-proxy-agent ``` -------------------------------- ### Install Playwright and Dependencies (npm) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/ci.md Installs npm packages and Playwright browsers with system dependencies using npm. This is a common setup step for Node.js projects in CI. ```bash # Install NPM packages npm ci # Install Playwright browsers and dependencies npx playwright install --with-deps ``` -------------------------------- ### TestInfo.titlePath Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/test-api/class-testinfo.md Gets the full title path of the test, starting with the test file name. ```APIDOC ## property: TestInfo.titlePath ### Description The full title path starting with the test file name. ### Type <[Array]<[string]>> ### Since v1.10 ``` -------------------------------- ### Start Development Server Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/tests/components/ct-vue-cli/README.md Compiles the project and starts a local development server with hot-reloading. Useful for active development. ```bash npm run serve ``` -------------------------------- ### Record with custom setup in Python (sync) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/codegen.md Utilize the sync API to launch Chromium, configure a custom context with routing, and pause the page to initiate manual recording. ```python from playwright.sync_api import sync_playwright with sync_playwright() as p: # Make sure to run headed. browser = p.chromium.launch(headless=False) # Setup context however you like. context = browser.new_context() # Pass any options context.route('**/*', lambda route: route.continue_()) # Pause the page, and start recording manually. page = context.new_page() page.pause() ``` -------------------------------- ### Configure Project Dependencies in Playwright Config Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/release-notes-js.md Define dependencies between projects in playwright.config.ts to manage setup artifacts and ensure proper execution order. This example shows a 'setup' project that other projects depend on. ```javascript 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'], }, ], }); ``` -------------------------------- ### Configure Projects with Dependencies Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/test-projects-js.md Set up projects where some depend on a 'setup' project. This ensures that the setup tasks are completed before the dependent tests run. ```javascript 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'], }, ], }); ``` -------------------------------- ### Python Sync selectOption Examples Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/input.md Provides synchronous option selection examples in Python for single and multiple selections using value or label. ```python # Single selection matching the value or label page.get_by_label('Choose a color').select_option('blue') # Single selection matching the label page.get_by_label('Choose a color').select_option(label='Blue') # Multiple selected items page.get_by_label('Choose multiple colors').select_option(['red', 'green', 'blue']) ``` -------------------------------- ### Record Trace on Test Failure (NUnit) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/trace-viewer.md Configures NUnit tests to start tracing at the beginning of a test and stop tracing at the end, saving the trace only if the test fails. Requires setup in [SetUp] and [TearDown] methods. ```csharp namespace PlaywrightTests; [Parallelizable(ParallelScope.Self)] [TestFixture] public class ExampleTest : PageTest { [SetUp] public async Task Setup() { await Context.Tracing.StartAsync(new() { Title = $"{TestContext.CurrentContext.Test.ClassName}.{TestContext.CurrentContext.Test.Name}", Screenshots = true, Snapshots = true, Sources = true }); } [TearDown] public async Task TearDown() { var failed = TestContext.CurrentContext.Result.Outcome == NUnit.Framework.Interfaces.ResultState.Error || TestContext.CurrentContext.Result.Outcome == NUnit.Framework.Interfaces.ResultState.Failure; await Context.Tracing.StopAsync(new() { Path = failed ? Path.Combine( TestContext.CurrentContext.WorkDirectory, "playwright-traces", $"{TestContext.CurrentContext.Test.ClassName}.{TestContext.CurrentContext.Test.Name}.zip" ) : null, }); } [Test] public async Task GetStartedLink() { // .. } } ``` -------------------------------- ### Route.fallback with method Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/api/class-route.md Demonstrates how to change the request method using `route.fallback`. For example, changing a request from GET to POST. ```APIDOC ## Route.fallback with method ### Description Allows changing the request method when using `route.fallback`. For example, you can change the method from GET to POST. ### Method `route.fallback(options)` ### Parameters #### Options - **method** (string) - Required - If set changes the request method (e.g. GET or POST). ### Request Example ```json { "method": "POST" } ``` ### Response This method does not return a response body, it modifies the request behavior. ``` -------------------------------- ### Complete API Test Example in C# Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/api-testing-csharp.md This comprehensive example shows how to set up API testing, create issues, and verify them using Playwright's APIRequestContext in C#. It includes setup, test execution, and cleanup methods. ```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(); } } ``` -------------------------------- ### Authenticate and Save State in Setup Project Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/auth.md This script performs login actions and saves the authenticated state to a file. It's intended to be run once in a setup project before other tests. ```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 }); }); ``` -------------------------------- ### Record with custom setup in Java Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/codegen.md Initialize Playwright, launch Chromium in headed mode, and configure a custom browser context with routing before pausing for manual recording. ```java import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType chromium = playwright.chromium(); // Make sure to run headed. Browser browser = chromium.launch(new BrowserType.LaunchOptions().setHeadless(false)); // Setup context however you like. BrowserContext context = browser.newContext(/* pass any options */); context.route("**/*", route -> route.resume()); // Pause the page, and start recording manually. Page page = context.newPage(); page.pause(); } } } ``` -------------------------------- ### Create and Click a Locator Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/writing-tests-js.md Demonstrates creating a locator for a 'Get started' link and then clicking it. Playwright automatically waits for the element to be actionable. ```javascript // Create a locator. const getStarted = page.getByRole('link', { name: 'Get started' }); // Click it. await getStarted.click(); ``` -------------------------------- ### Configure Single-Page App Mode Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/tests/components/ct-svelte/README.md Modify the 'start' command in package.json to enable single-page app mode, allowing sirv to serve any path. ```json "start": "sirv public --single" ``` -------------------------------- ### Get and Deconstruct Console Log Arguments in C# Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/api/class-consolemessage.md This example demonstrates how to asynchronously wait for a console message and access its arguments in C# with Playwright. ```csharp // Get the next console message var waitForMessageTask = page.WaitForConsoleMessageAsync(); await page.EvaluateAsync("console.log('hello', 42, { foo: 'bar' });"); var message = await waitForMessageTask; // Deconstruct console.log arguments await message.Args.ElementAt(0).JsonValueAsync(); // hello await message.Args.ElementAt(1).JsonValueAsync(); // 42 ``` -------------------------------- ### Start Selenium Node Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/selenium-grid.md Starts a Selenium node and registers it with the Selenium Grid hub. Ensure the SE_NODE_GRID_URL environment variable points to your hub. ```bash SE_NODE_GRID_URL="http://:4444" java -jar selenium-server-.jar node ``` -------------------------------- ### Get and Deconstruct Console Log Arguments in Java Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/api/class-consolemessage.md This example demonstrates how to wait for a console message and then access its arguments using Java with Playwright. ```java // Get the next console message ConsoleMessage msg = page.waitForConsoleMessage(() -> { // Issue console.log inside the page page.evaluate("console.log('hello', 42, { foo: 'bar' });"); }); // Deconstruct console.log arguments msg.args().get(0).jsonValue(); // hello msg.args().get(1).jsonValue(); // 42 ``` -------------------------------- ### Install Browsers and Dependencies (C#) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/browsers.md Installs the Chromium browser along with its system dependencies in a single command using PowerShell. ```bash pwsh bin/Debug/netX/playwright.ps1 install --with-deps chromium ``` -------------------------------- ### Reporter.onTestBegin Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/test-reporter-api/class-reporter.md Called after a test has started in the worker process. It receives the test case and the test result object which gets populated as the test runs. ```APIDOC ## optional method: Reporter.onTestBegin ### Description Called after a test has been started in the worker process. ### Parameters * **test** ([TestCase]) - The test that has been started. * **result** ([TestResult]) - The result of the test run, this object gets populated while the test runs. ``` -------------------------------- ### Configure Multiple Web Servers Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/test-webserver-js.md Launch multiple web servers concurrently by providing an array of `webServer` configurations. This example sets up both a frontend and a backend server. ```typescript import { defineConfig } from '@playwright/test'; export default defineConfig({ webServer: [ { command: 'npm run start', url: 'http://localhost:3000', name: 'Frontend', timeout: 120 * 1000, reuseExistingServer: !process.env.CI, }, { command: 'npm run backend', url: 'http://localhost:3333', name: 'Backend', timeout: 120 * 1000, reuseExistingServer: !process.env.CI, } ], use: { baseURL: 'http://localhost:3000', }, }); ``` -------------------------------- ### Svelte Component Test Setup Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/test-components-js.md Example of setting up a component test for a Svelte application using @playwright/experimental-ct-svelte. Includes viewport configuration and mounting with props. ```javascript import { test, expect } from '@playwright/experimental-ct-svelte'; import HelloWorld from './HelloWorld.svelte'; test.use({ viewport: { width: 500, height: 500 } }); test('should work', async ({ mount }) => { const component = await mount(HelloWorld, { props: { msg: 'Greetings', }, }); await expect(component).toContainText('Greetings'); }); ``` -------------------------------- ### Install Beta Firefox for Bidi Tests Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/tests/bidi/README.md Install the beta channel of Firefox to use with BiDi tests. This command should be run from the project root. ```sh npx -y @puppeteer/browsers install firefox@beta ``` -------------------------------- ### Record with custom setup in C# Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/codegen.md Instantiate Playwright, launch Chromium in headed mode, and set up a custom browser context with routing before pausing for manual recording. ```csharp using Microsoft.Playwright; using var playwright = await Playwright.CreateAsync(); var chromium = playwright.Chromium; // Make sure to run headed. var browser = await chromium.LaunchAsync(new() { Headless = false }); // Setup context however you like. var context = await browser.NewContextAsync(); // Pass any options await context.RouteAsync("**/*", route => route.ContinueAsync()); // Pause the page, and start recording manually. var page = await context.NewPageAsync(); await page.PauseAsync(); ``` -------------------------------- ### Vue Component Test Setup Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/test-components-js.md Example of setting up a component test for a Vue application using @playwright/experimental-ct-vue. Includes viewport configuration and mounting with props. ```javascript import { test, expect } from '@playwright/experimental-ct-vue'; import HelloWorld from './HelloWorld.vue'; test.use({ viewport: { width: 500, height: 500 } }); test('should work', async ({ mount }) => { const component = await mount(HelloWorld, { props: { msg: 'Greetings', }, }); await expect(component).toContainText('Greetings'); }); ``` -------------------------------- ### Get and Deconstruct Console Log Arguments in Python (Sync) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/api/class-consolemessage.md This example shows how to synchronously wait for a console message and access its arguments in Python with Playwright. ```python # Get the next console log with page.expect_console_message() as msg_info: # Issue console.log inside the page page.evaluate("console.log('hello', 42, { foo: 'bar' })") msg = msg_info.value # Deconstruct print arguments msg.args[0].json_value() # hello msg.args[1].json_value() # 42 ``` -------------------------------- ### Install Playwright with yarn Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/intro-js.md Use this command to initialize Playwright with yarn. Follow the prompts to configure your project. ```bash yarn create playwright ``` -------------------------------- ### Get and Deconstruct Console Log Arguments in Python (Async) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/api/class-consolemessage.md This example shows how to asynchronously wait for a console message and access its arguments in Python with Playwright. ```python # Get the next console log async with page.expect_console_message() as msg_info: # Issue console.log inside the page await page.evaluate("console.log('hello', 42, { foo: 'bar' })") msg = await msg_info.value # Deconstruct print arguments await msg.args[0].json_value() # hello await msg.args[1].json_value() # 42 ``` -------------------------------- ### Puppeteer Test Example with Jest Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/puppeteer-js.md A Puppeteer test case using Jest to verify content 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()); }); ``` -------------------------------- ### Upload Files with setInputFiles in Java Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/input.md Demonstrates selecting single files, multiple files, directories, clearing selections, and uploading buffers from memory using Java. ```java // Select one file page.getByLabel("Upload file").setInputFiles(Paths.get("myfile.pdf")); // Select multiple files page.getByLabel("Upload files").setInputFiles(new Path[] {Paths.get("file1.txt"), Paths.get("file2.txt")}); // Select a directory page.getByLabel("Upload directory").setInputFiles(Paths.get("mydir")); // Remove all the selected files page.getByLabel("Upload file").setInputFiles(new Path[0]); // Upload buffer from memory page.getByLabel("Upload file").setInputFiles(new FilePayload( "file.txt", "text/plain", "this is test".getBytes(StandardCharsets.UTF_8))); ``` -------------------------------- ### Install Browsers from Custom Host (PowerShell) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/browsers.md Set the PLAYWRIGHT_DOWNLOAD_HOST environment variable in PowerShell to download Playwright browsers from a specified custom URL. This example is for PowerShell. ```js $Env:PLAYWRIGHT_DOWNLOAD_HOST="http://192.0.2.1" npx playwright install ``` ```python $Env:PLAYWRIGHT_DOWNLOAD_HOST="http://192.0.2.1" pip install playwright playwright install ``` ```java $Env:PLAYWRIGHT_DOWNLOAD_HOST="http://192.0.2.1" mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install" ``` ```csharp $Env:PLAYWRIGHT_DOWNLOAD_HOST="http://192.0.2.1" pwsh bin/Debug/netX/playwright.ps1 install ``` -------------------------------- ### Install Playwright with pnpm Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/intro-js.md Use this command to initialize Playwright with pnpm. Follow the prompts to configure your project. ```bash pnpm create playwright ``` -------------------------------- ### Python Async Example for ElementHandle.evalOnSelector Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/api/class-elementhandle.md Illustrates the asynchronous usage of ElementHandle.evalOnSelector in Python to get specific text content. Use with caution as it bypasses element actionability checks. ```python tweet_handle = await page.query_selector(".tweet") assert await tweet_handle.eval_on_selector(".like", "node => node.innerText") == "100" assert await tweet_handle.eval_on_selector(".retweets", "node => node.innerText") == "10" ``` -------------------------------- ### Deploy to Surge Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/tests/components/ct-svelte/README.md Install the Surge CLI, build your Svelte app for production, and then deploy the public directory to Surge. ```bash npm install -g surge npm run build surge public my-project.surge.sh ``` -------------------------------- ### Get and Deconstruct Console Log Arguments in JavaScript Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/api/class-consolemessage.md This example shows how to wait for the next console message and then access and parse its individual arguments using JSON value. ```javascript // Get the next console log const msgPromise = page.waitForEvent('console'); await page.evaluate(() => { console.log('hello', 42, { foo: 'bar' }); // Issue console.log inside the page }); const msg = await msgPromise; // Deconstruct console log arguments await msg.args()[0].jsonValue(); // hello await msg.args()[1].jsonValue(); // 42 ``` -------------------------------- ### Upload Files with set_input_files in Python (Sync) Source: https://github.com/ruifigueira/playwright-crx/blob/main/playwright/docs/src/input.md Demonstrates selecting single files, multiple files, directories, clearing selections, and uploading buffers from memory using synchronous Python. ```python # Select one file page.get_by_label("Upload file").set_input_files('myfile.pdf') # Select multiple files page.get_by_label("Upload files").set_input_files(['file1.txt', 'file2.txt']) # Select a directory page.get_by_label("Upload directory").set_input_files('mydir') # Remove all the selected files page.get_by_label("Upload file").set_input_files([]) # Upload buffer from memory page.get_by_label("Upload file").set_input_files( files=[ {"name": "test.txt", "mimeType": "text/plain", "buffer": b"this is a test"} ], ) ```