=============== LIBRARY RULES =============== From library maintainers: - Use crossBrowserSuite() to write tests that run across Chromium, Firefox, and WebKit - Use page.locator() to find elements by CSS selector - Use page.expectTitle(), page.expectURL(), element.expectVisible() for assertions - Use ensureAll() to auto-install browsers and system dependencies - Always import from 'unibrowser' package - TypeScript ESM only, require module: Node16 in tsconfig ### Install Unibrowser Package Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/getting-started.md Installs the unibrowser package using npm. This is the first step to using the library in your project. ```bash npm install unibrowser ``` -------------------------------- ### Programmatically Install Browsers and Dependencies Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/getting-started.md Ensures all necessary system dependencies (on Linux) and browser binaries are installed using the Unibrowser API. This provides a programmatic alternative to the command-line installations. ```typescript import { ensureAll } from "unibrowser"; ensureAll(); // installs system deps (Linux) + all browsers ``` -------------------------------- ### Perform One-Step Setup with ensureAll Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/manager.md Installs all required system dependencies for Linux and downloads all supported browsers. This is a convenience wrapper for full environment preparation. ```typescript import { ensureAll } from "unibrowser"; ensureAll(); ``` -------------------------------- ### Write Your First Cross-Browser Test Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/getting-started.md An example of an end-to-end test written using Unibrowser and Vitest. It demonstrates how to define a cross-browser suite and write individual tests that run across different browsers. ```typescript import { expect } from "vitest"; import { crossBrowserSuite } from "unibrowser"; crossBrowserSuite("Example", (test) => { test("loads page", async ({ page }) => { await page.goto("https://example.com"); await page.expectTitle("Example Domain"); }); test("has correct heading", async ({ page }) => { const h1 = page.locator("h1"); await h1.expectText("Example Domain"); }); test("has link to IANA", async ({ page }) => { const link = page.locator("a"); const href = await link.getAttribute("href"); expect(href).toContain("iana.org"); }); }); ``` -------------------------------- ### Install Playwright System Dependencies (Linux) Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/getting-started.md Installs system-level dependencies required by Playwright on Linux distributions. This is crucial for the browsers to function correctly. ```bash npx playwright install-deps ``` -------------------------------- ### Install Playwright Browsers Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/getting-started.md Installs the necessary browser binaries (Chromium, Firefox, WebKit) required by Playwright, which Unibrowser utilizes. This command ensures you have the environments to run your cross-browser tests. ```bash npx playwright install chromium firefox webkit ``` -------------------------------- ### Install unibrowser and browser dependencies Source: https://github.com/theforgivenone/unibrowser/blob/main/skills/cross-browser-e2e/SKILL.md Commands to install the unibrowser package and the necessary browser binaries and system dependencies for cross-browser testing. ```bash npm install unibrowser npx playwright install chromium firefox webkit npx playwright install-deps ``` -------------------------------- ### Install System Dependencies with ensureDependencies Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/manager.md Installs necessary system-level dependencies required for browser execution on Linux. On non-Linux platforms, this function logs a skip message. ```typescript import { ensureDependencies } from "unibrowser"; ensureDependencies(); ``` -------------------------------- ### GitHub Actions Workflow for E2E Tests Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/ci-cd.md This GitHub Actions workflow automates End-to-End tests for Unibrowser. It checks out the code, sets up Node.js, installs dependencies, installs Playwright browsers, and runs the tests using Vitest. ```yaml name: E2E Testson: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 20 cache: npm - run: npm ci - name: Install browsers run: npx playwright install --with-deps chromium firefox webkit - name: Run tests run: npx vitest run ``` -------------------------------- ### Dockerfile for Unibrowser CI/CD Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/ci-cd.md This Dockerfile sets up an environment to run Unibrowser tests. It starts from a Playwright base image, installs npm dependencies, copies the project code, and executes the Vitest tests. ```dockerfile FROM mcr.microsoft.com/playwright:v1.48.0-noble WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npx vitest run ``` -------------------------------- ### Programmatic Browser Installation with Unibrowser Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/ci-cd.md These TypeScript snippets demonstrate how to programmatically install Playwright browsers and system dependencies using Unibrowser's `ensureAll()` and `ensureBrowsers()` functions. This avoids manual installation steps in CI environments. ```typescript // vitest.setup.ts import { ensureAll } from "unibrowser"; ensureAll(); // installs browsers + system deps ``` ```typescript import { ensureBrowsers } from "unibrowser"; beforeAll(() => { ensureBrowsers({ browsers: ["chromium", "firefox", "webkit"] }); }); ``` -------------------------------- ### Install Browsers with ensureBrowsers Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/manager.md Downloads missing browsers using Playwright. Supports installing specific browsers, forcing a reinstall, and defaults to installing all six supported browsers. ```typescript import { ensureBrowsers } from "unibrowser"; // Install all missing browsers ensureBrowsers(); // Install only specific browsers ensureBrowsers({ browsers: ["chromium", "firefox"] }); // Force reinstall ensureBrowsers({ force: true }); ``` -------------------------------- ### Run End-to-End Tests Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/getting-started.md Executes all end-to-end tests defined in your project using Vitest. The output shows tests running sequentially across Chromium, Firefox, and WebKit. ```bash npx vitest run ``` -------------------------------- ### Installing Unibrowser and Playwright Browsers (Bash) Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/index.md Installs the Unibrowser npm package and downloads the necessary browser binaries (Chromium, Firefox, and WebKit) required for cross-browser testing via Playwright. This is a prerequisite for running Unibrowser tests. ```bash npm install unibrowser npx playwright install chromium firefox webkit ``` -------------------------------- ### Programmatically Ensure Browser Installation for unibrowser (TypeScript) Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/README.md This TypeScript code snippet programmatically ensures that all necessary browsers and system dependencies for unibrowser are downloaded and installed. Calling `ensureAll()` handles the browser installation process, making it convenient for automated setups or when manual installation via the command line is not preferred. This function is part of the unibrowser package. ```typescript import { ensureAll } from "unibrowser"; ensureAll(); // downloads browsers + system deps ``` -------------------------------- ### Run Tests in Watch Mode Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/getting-started.md Starts Vitest in watch mode, which automatically re-runs tests when file changes are detected. This is useful for iterative development. ```bash npx vitest ``` -------------------------------- ### Check Browser Status and Availability Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/manager.md Provides various utilities to inspect the installation status of browsers. Includes functions to check individual browser status, list all statuses, identify missing browsers, and verify installation via boolean flags. ```typescript const status = getBrowserStatus("chromium"); const statuses = getAllBrowserStatus(); const missing = getMissingBrowsers(); if (isBrowserInstalled("chromium")) { // ready to launch } printBrowserStatus(); ``` -------------------------------- ### Cross-Browser E2E Test Suite with Unibrowser (TypeScript) Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/index.md Demonstrates how to define a cross-browser test suite using Unibrowser's `crossBrowserSuite` function. This example tests the homepage of 'example.com' across different browsers, asserting the title and heading text. It requires the 'unibrowser' package. ```typescript import { crossBrowserSuite } from "unibrowser"; crossBrowserSuite("My App", (test) => { test("loads homepage", async ({ page }) => { await page.goto("https://example.com"); await page.expectTitle("Example Domain"); const h1 = page.locator("h1"); await h1.expectText("Example Domain"); }); }); ``` -------------------------------- ### Validate Browser Installation with validateBrowser Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/manager.md Checks if a specific browser is installed. If not, it throws an error containing instructions on how to install the missing browser via the command line. ```typescript try { validateBrowser("chromium"); } catch (e) { // "Browser 'chromium' (chromium) is not installed. Run: npx playwright install chromium" } ``` -------------------------------- ### Run Only E2E Tests Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/getting-started.md Filters the Vitest execution to run only the tests located within the `tests/e2e` directory. This allows for focused testing during development. ```bash npx vitest run tests/e2e ``` -------------------------------- ### Type Checking Commands Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/getting-started.md Provides commands for performing type checking on your TypeScript codebase. `npm run typecheck` uses `tsc --noEmit` for standard TypeScript checks, while `npm run pyright` uses Pyright for Python interop type checking. ```bash npm run typecheck # tsc --noEmit npm run pyright # pyright (Python interop) ``` -------------------------------- ### Unibrowser Headless Mode Example Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/ci-cd.md This TypeScript code snippet illustrates launching a browser in headless mode with Unibrowser. Headless mode is the default behavior, making it suitable for CI environments without requiring extra configuration. ```typescript const browser = await UniBrowser.launch("chromium"); // headless: true is default ``` -------------------------------- ### Implement Authentication Flow Test Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/cross-browser.md A comprehensive example demonstrating a login flow, including form interaction, validation, and navigation assertions across multiple browsers. ```typescript import { expect } from "vitest"; import { crossBrowserSuite } from "unibrowser"; crossBrowserSuite("Authentication", (test) => { test("displays login form", async ({ page }) => { await page.goto("https://myapp.com/login"); await page.getByLabel("Email").expectVisible(); await page.getByLabel("Password").expectVisible(); await page.getByRole("button", { name: "Sign in" }).expectVisible(); }); test("logs in successfully", async ({ page }) => { await page.goto("https://myapp.com/login"); await page.getByLabel("Email").type("user@test.com"); await page.getByLabel("Password").type("correctpassword"); await page.getByRole("button", { name: "Sign in" }).click(); await page.waitForURL("**/dashboard"); await page.expectURLContains("/dashboard"); }); }); ``` -------------------------------- ### TypeScript Configuration for ESM Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/getting-started.md Configures the TypeScript compiler to use modern ECMAScript module standards (ESM). This is a requirement for Unibrowser and ensures proper module resolution and targeting. ```json { "compilerOptions": { "module": "Node16", "moduleResolution": "Node16", "target": "ES2022", "strict": true } } ``` -------------------------------- ### Full API Mocking and Offline Test Suite Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/network.md A comprehensive example showing how to integrate network mocking and offline simulation within a test suite using Unibrowser and Vitest. ```typescript import { crossBrowserSuite } from "unibrowser"; import { expect } from "vitest"; crossBrowserSuite("API Mocking", (test) => { test("displays mocked user data", async ({ page }) => { await page.raw.context().route("**/api/user", (route) => { route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ name: "Mocked User" }), }); }); await page.goto("https://myapp.com/profile"); const name = await page.locator(".user-name").innerText(); expect(name).toBe("Mocked User"); }); test("handles offline gracefully", async ({ page }) => { await page.goto("https://myapp.com"); await page.raw.context().setOffline(true); await page.locator("button.refresh").click(); await page.locator(".offline-banner").expectVisible(); }); }); ``` -------------------------------- ### Install Browsers for unibrowser (Bash) Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/README.md This command installs the necessary browsers (Chromium, Firefox, and WebKit) required by Playwright, which unibrowser relies on for cross-browser testing. These browsers are essential for running the E2E tests across different rendering engines. This is typically run once after installing the unibrowser package. ```bash npx playwright install chromium firefox webkit ``` -------------------------------- ### Manage Storage State in a Context Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/context.md Enables getting the serialized storage state (cookies and localStorage) of a context, which can be used to save and restore sessions. ```typescript const state = await context.storageState(); // Save to file, then restore later: const context2 = await browser.newContext({ storageState: state }); ``` -------------------------------- ### Get the Number of Matching Elements Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/element.md Returns the total count of elements that match the given locator. This is useful for verifying the number of items present on the page. ```typescript const count = await page.locator("li").count(); ``` -------------------------------- ### Browser Status Interface (TypeScript) Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/reference/types.md Defines the `BrowserStatus` interface, providing information about a specific browser's installation status. Includes `name`, `type`, whether it's `installed`, and its installation `path`. ```typescript interface BrowserStatus { name: BrowserName; type: BrowserType; installed: boolean; path: string | null; } ``` -------------------------------- ### GitLab CI Configuration for E2E Tests Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/ci-cd.md This GitLab CI configuration defines a job to run End-to-End tests for Unibrowser. It uses a Playwright Docker image, installs dependencies, and executes the tests using Vitest. It also includes caching for node_modules. ```yaml e2e-tests: image: mcr.microsoft.com/playwright:v1.48.0-noble script: - npm ci - npx vitest run cache: key: ${CI_COMMIT_REF_SLUG} paths: - node_modules/ ``` -------------------------------- ### Browser Ensure Options Interface (TypeScript) Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/reference/types.md Defines the `EnsureOptions` interface for managing browser installations. Allows specifying an array of `browsers` to ensure are installed and a `force` flag to re-download even if already present. ```typescript interface EnsureOptions { browsers?: BrowserName[]; force?: boolean; } ``` -------------------------------- ### Browser management and evaluation Source: https://github.com/theforgivenone/unibrowser/blob/main/skills/cross-browser-e2e/SKILL.md Utilities for executing custom JavaScript in the browser context and managing browser installation status. ```typescript import { ensureAll, printBrowserStatus } from "unibrowser"; // Evaluate JS const title = await page.evaluate(() => document.title); // Management ensureAll(); printBrowserStatus(); ``` -------------------------------- ### Conditional Request Handling Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/network.md Demonstrates logic-based interception where requests are handled differently based on the HTTP method (e.g., mocking GET requests while passing through others). ```typescript await context.route("**/api/users", (route) => { if (route.request().method() === "GET") { route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify([{ id: 1, name: "Alice" }]), }); } else { route.continue(); } }); ``` -------------------------------- ### Get Element Bounding Box Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/element.md Retrieves the bounding box of an element, including its position (x, y) and dimensions (width, height). Returns null if the element is not found or not visible. ```typescript const box = await page.locator("h1").boundingBox(); // { x: 100, y: 50, width: 200, height: 30 } ``` -------------------------------- ### Get Element Attribute Value Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/element.md Retrieves the value of a specified attribute for an element. Returns null if the attribute is not present on the element. ```typescript const href = await page.locator("a").getAttribute("href"); const id = await page.locator("div").getAttribute("id"); ``` -------------------------------- ### Get Specific Elements from a Group Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/element.md Retrieves the first, last, or an element at a specific index from a collection of matching elements. This is useful when a selector matches multiple elements and you need to target one precisely. ```typescript const firstLink = page.locator("a").first(); const secondItem = page.locator("li").nth(1); ``` -------------------------------- ### POST /launch Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/unibrowser.md Launches a specified browser instance with optional configuration settings. ```APIDOC ## POST /launch ### Description Launches a browser instance. Validates that the browser is installed before initialization. ### Method POST ### Parameters #### Request Body - **browser** (BrowserName) - Required - One of: "chromium", "chrome", "edge", "firefox", "safari", "webkit" - **options.headless** (boolean) - Optional - Run without UI (default: true) - **options.slowMo** (number) - Optional - Slow down actions by ms - **options.proxy** (object) - Optional - Proxy server configuration { server, username?, password? } ### Request Example { "browser": "chromium", "options": { "headless": true } } ### Response #### Success Response (200) - **browser** (UniBrowser) - The initialized browser instance. #### Response Example { "status": "success", "instance": "[UniBrowser Instance]" } ``` -------------------------------- ### Launch Browser Instances with UniBrowser Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/unibrowser.md Demonstrates how to initialize browser instances using UniBrowser.launch and UniBrowser.ensureAndLaunch, supporting various browser types and configuration options like headless mode. ```typescript import { UniBrowser } from "unibrowser"; const browser = await UniBrowser.launch("chromium", { headless: true }); const chromium = await UniBrowser.launch("chromium"); const firefox = await UniBrowser.launch("firefox"); const safari = await UniBrowser.launch("webkit"); const ensuredBrowser = await UniBrowser.ensureAndLaunch("chromium"); ``` -------------------------------- ### Navigate pages with UniPage Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/page.md Demonstrates how to navigate to a specific URL using the page.goto method. ```typescript const response = await page.goto("https://example.com"); ``` -------------------------------- ### Manage Browser Pages and Contexts Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/unibrowser.md Shows how to create new pages for quick navigation and new contexts for isolated browsing sessions with custom configurations like viewports, user agents, and permissions. ```typescript const page = await browser.newPage({ viewport: { width: 1920, height: 1080 } }); await page.goto("https://example.com"); const context = await browser.newContext({ viewport: { width: 1920, height: 1080 }, userAgent: "custom-agent", locale: "en-US", timezoneId: "America/New_York", colorScheme: "dark", ignoreHTTPSErrors: true, permissions: ["geolocation"] }); const contextPage = await context.newPage(); ``` -------------------------------- ### Perform user interactions Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/page.md Methods for simulating user actions such as clicking, typing, filling inputs, pressing keys, and selecting options. ```typescript await page.click("button.submit"); await page.fill('input[name="email"]', "user@test.com"); await page.type("input", "hello", { delay: 50 }); await page.press("input", "Enter"); await page.selectOption("select.color", "red"); ``` -------------------------------- ### Retrieve Platform Information with getPlatformInfo Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/manager.md Returns details about the current operating system, CPU architecture, and the list of browser types supported on the host machine. ```typescript const info = getPlatformInfo(); // { os: "linux", arch: "x64", supported: ["chromium", "firefox", "webkit"] } ``` -------------------------------- ### Wait for page states and elements Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/page.md Synchronization utilities to pause execution until specific elements appear, URLs match, or load states are reached. ```typescript const el = await page.waitForSelector(".loading-done", { state: "visible" }); await page.waitForURL("**/dashboard"); await page.waitForLoadState("networkidle"); await page.waitForFunction(() => document.title === "Done"); ``` -------------------------------- ### Assert page state and content Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/page.md Methods to verify page titles and URLs using exact strings or regular expressions. ```typescript await page.expectTitle("My App"); await page.expectTitle(/My App/); await page.expectTitleContains("Dashboard"); await page.expectURL("**/dashboard"); await page.expectURL(//dashboard/); await page.expectURLContains("dashboard"); ``` -------------------------------- ### Manage Pages within a Context Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/context.md Provides methods to create new pages within an existing context and retrieve a list of all currently open pages. ```typescript const page = await context.newPage(); ``` ```typescript const pages = context.pages(); ``` -------------------------------- ### Execute Static Analysis Commands Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/pyright.md Commands to run Pyright for Python type stubs and TypeScript's tsc for project-wide type validation. ```bash npm run pyright # or npx pyright ``` ```bash npm run typecheck ``` ```bash npm run typecheck # TypeScript npm run pyright # Python stubs ``` -------------------------------- ### Execute Test Commands Source: https://github.com/theforgivenone/unibrowser/blob/main/skills/cross-browser-e2e/SKILL.md Provides standard commands for running Vitest suites, including full test runs, directory-specific execution, and browser-specific npm scripts. ```bash npx vitest run # All tests npx vitest run tests/e2e # E2E only npx vitest # Watch mode # Browser-specific npm run test:chromium # Chromium only npm run test:firefox # Firefox only npm run test:webkit # WebKit only ``` -------------------------------- ### Running Tests with Vitest (Bash) Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/index.md This command executes the test suite defined using Unibrowser and Vitest. It assumes Vitest is configured in the project. The output shows the test results for each browser. ```bash npx vitest run ``` -------------------------------- ### Execute custom JavaScript Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/page.md Run arbitrary JavaScript code within the context of the browser page. ```typescript const title = await page.evaluate(() => document.title); const result = await page.evaluate(() => { return document.querySelectorAll("a").length; }); ``` -------------------------------- ### Create a New Browser Context Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/context.md Creates a new isolated browser context with specified viewport settings. Alternatively, a context can be created implicitly when a new page is requested. ```typescript const context = await browser.newContext({ viewport: { width: 1920, height: 1080 }, }); ``` ```typescript const page = await browser.newPage(); // creates context internally ``` -------------------------------- ### Capture and compare screenshots Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/page.md Utilities for taking page screenshots and performing visual regression testing against baseline images. ```typescript const png = await page.screenshot(); const full = await page.screenshot({ fullPage: true }); const jpeg = await page.screenshot({ type: "jpeg", quality: 80 }); await page.expectScreenshot("./screenshots/home.png"); ``` -------------------------------- ### POST /context Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/unibrowser.md Creates a new isolated browser context for managing sessions, cookies, and storage. ```APIDOC ## POST /context ### Description Creates a new browser context for isolated sessions. ### Method POST ### Parameters #### Request Body - **viewport** (object) - Optional - { width, height } - **userAgent** (string) - Optional - Custom user agent string - **locale** (string) - Optional - Browser locale - **timezoneId** (string) - Optional - Timezone ID - **colorScheme** (string) - Optional - "light", "dark", or "no-preference" - **ignoreHTTPSErrors** (boolean) - Optional - Skip HTTPS errors - **permissions** (string[]) - Optional - Browser permissions ### Request Example { "viewport": { "width": 1920, "height": 1080 }, "colorScheme": "dark" } ### Response #### Success Response (200) - **context** (UniContext) - The created browser context. #### Response Example { "status": "success", "contextId": "ctx_12345" } ``` -------------------------------- ### Accessing Default Configuration in TypeScript Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/reference/config.md Demonstrates how to import and inspect the default configuration object provided by the Unibrowser library. ```typescript import { DEFAULTS } from "unibrowser"; console.log(DEFAULTS.viewport); // { width: 1280, height: 720 } ``` -------------------------------- ### Perform Visual Regression Testing Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/screenshots.md Explains how to compare current page states against baseline images using expectScreenshot and manual buffer comparison. Includes handling for cross-browser differences via threshold settings. ```typescript await page.expectScreenshot("./screenshots/homepage.png"); // Allow up to 5% difference await page.expectScreenshot("./baseline.png", 5); import { compareScreenshots } from "unibrowser"; const result = await compareScreenshots(actualBuffer, expectedBuffer); crossBrowserSuite("Visual", (test) => { test("homepage looks correct", async ({ page }) => { await page.goto("https://example.com"); await page.expectScreenshot(`./screenshots/home.png`, 2); }); }); ``` -------------------------------- ### Assertions for pages and elements Source: https://github.com/theforgivenone/unibrowser/blob/main/skills/cross-browser-e2e/SKILL.md Built-in assertion helpers to verify page URLs/titles and specific element properties like visibility, text, or attributes. ```typescript // Page assertions await page.expectTitle("My App"); await page.expectURLContains("dashboard"); // Element assertions await el.expectVisible(); await el.expectText("Welcome"); await el.expectAttribute("href", "/dashboard"); ``` -------------------------------- ### Configure Screenshot Options and File Saving Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/screenshots.md Shows how to save screenshots to specific file paths with custom formats like JPEG, including quality settings and region clipping. ```typescript await page.screenshot({ path: "./screenshots/homepage.png" }); await page.screenshot({ path: "./screenshots/homepage.jpg", type: "jpeg", quality: 90 }); const buffer = await page.screenshot({ fullPage: true }); const buffer = await page.screenshot({ clip: { x: 0, y: 0, width: 800, height: 600 }, }); ``` -------------------------------- ### POST /context/setOffline Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/network.md Simulates offline network conditions for the browser context. ```APIDOC ## POST context.setOffline(offline) ### Description Simulates offline network conditions. When set to true, all network requests will fail. ### Method POST ### Endpoint context.setOffline(offline) ### Parameters #### Request Body - **offline** (boolean) - Required - True to enable offline mode, false to restore connectivity. ### Request Example ```javascript await context.setOffline(true); ``` ``` -------------------------------- ### Accessing Supported Browsers List Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/reference/config.md Retrieves the list of supported browser engines used by default in cross-browser test suites. ```typescript import { ALL_BROWSERS } from "unibrowser"; // ["chromium", "firefox", "webkit"] ``` -------------------------------- ### Take Element Screenshot Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/element.md Takes a screenshot of a specific element and returns the image data as a Buffer. This allows for visual regression testing of individual components. ```typescript const buffer = await page.locator(".hero").screenshot(); ``` -------------------------------- ### Implement Network Interception Source: https://github.com/theforgivenone/unibrowser/blob/main/skills/cross-browser-e2e/SKILL.md Demonstrates how to mock API responses, block specific file types like images, and simulate offline network conditions using the page context routing API. ```typescript // Mock API await page.raw.context().route("**/api/user", (route) => { route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ name: "Test User" }), }); }); // Block images await page.raw.context().route("**/*.{png,jpg}", (route) => route.abort()); // Offline await page.raw.context().setOffline(true); ``` -------------------------------- ### Manage Permissions in a Context Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/context.md Allows granting specific browser permissions, optionally scoped to a particular origin, and revoking all granted permissions. ```typescript await context.grantPermissions(["geolocation", "notifications"]); await context.grantPermissions(["geolocation"], { origin: "https://example.com" }); ``` ```typescript await context.clearPermissions(); ``` -------------------------------- ### Find elements using selectors and locators Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/page.md Various methods to locate DOM elements based on CSS selectors, text content, ARIA roles, labels, placeholders, and test IDs. ```typescript const h1 = page.locator("h1"); const btn = page.locator("button.submit"); const el = page.locator("div", { hasText: "Hello" }); const elText = page.getByText("Click me"); const heading = page.getByRole("heading", { name: "Welcome" }); const btnRole = page.getByRole("button", { name: /submit/i }); const input = page.getByLabel("Email"); const placeholder = page.getByPlaceholder("Enter email"); const testId = page.getByTestId("login-button"); ``` -------------------------------- ### Close Browser Resources Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/unibrowser.md Illustrates the proper way to close browser instances to free system resources, including a recommended try-finally pattern for robust error handling. ```typescript await browser.close(); const browser = await UniBrowser.launch("chromium"); try { const page = await browser.newPage(); // ... tests ... } finally { await browser.close(); } ``` -------------------------------- ### Running Vitest Tests in Parallel with Limited Workers Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/ci-cd.md This bash command shows how to run Vitest tests in parallel while limiting the number of worker processes. This is useful for CI environments to manage resource consumption. ```bash npx vitest run --pool=forks --poolOptions.forks.maxForks=2 ``` -------------------------------- ### Configuring Unibrowser with loadConfig Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/reference/config.md Shows how to perform a deep-merge of custom settings onto the default configuration. This is useful for customizing headless mode, viewports, and timeouts. ```typescript import { loadConfig } from "unibrowser"; const config = loadConfig({ headless: false, viewport: { width: 1920, height: 1080 }, timeout: { navigation: 60000, action: 15000, expect: 10000 }, }); ``` -------------------------------- ### Capture Page and Element Screenshots with TypeScript Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/screenshots.md Demonstrates how to capture screenshots of the entire page or specific DOM elements using the page.screenshot method. Supports various configurations like full-page capture and file path specification. ```typescript const buffer = await page.screenshot(); const buffer = await page.screenshot({ fullPage: true }); const buffer = await page.screenshot({ path: "output.png" }); const h1 = page.locator("h1"); const buffer = await h1.screenshot(); ``` -------------------------------- ### Expand to All Matching Elements Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/element.md Retrieves all elements that match the locator and returns them as an array. This allows for iteration and processing of multiple elements. ```typescript const items = await page.locator("li").all(); for (const item of items) { const text = await item.innerText(); console.log(text); } ``` -------------------------------- ### Optimize Test Performance Source: https://github.com/theforgivenone/unibrowser/blob/main/skills/cross-browser-e2e/SKILL.md Configures Vitest for browser pool reuse to improve execution speed and sets navigation options for faster SPA loading. ```typescript // vitest.config.ts import { defineConfig } from "vitest/config"; export default defineConfig({ test: { pool: "threads", poolOptions: { threads: { singleThread: true }, }, }, }); ``` ```typescript const browser = await UniBrowser.launch("chromium", { waitUntil: "domcontentloaded" }); ``` -------------------------------- ### Browser Launch Options Interface (TypeScript) Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/reference/types.md Defines the `BrowserLaunchOptions` interface for configuring browser launch parameters. Options include headless mode, slow motion, devtools, viewport, user agent, locale, timezone, color scheme, HTTPS error handling, and proxy settings. ```typescript interface BrowserLaunchOptions { headless?: boolean; slowMo?: number; devtools?: boolean; viewport?: ViewportConfig | null; userAgent?: string; locale?: string; timezoneId?: string; colorScheme?: "light" | "dark" | "no-preference"; ignoreHTTPSErrors?: boolean; proxy?: { server: string; username?: string; password?: string; }; } ``` -------------------------------- ### Press a Keyboard Key Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/element.md Simulates pressing a keyboard key while the element is focused. Useful for triggering actions like 'Enter' or 'Escape'. ```typescript await page.locator("input").press("Enter"); ``` -------------------------------- ### Configure Pyright for Python Type Checking Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/pyright.md The pyrightconfig.json file defines the project's static analysis settings, including include/exclude paths, strict type checking mode, and Python environment specifications. ```json { "include": ["pyi", "src"], "exclude": ["node_modules", "dist"], "typeCheckingMode": "strict", "reportMissingImports": true, "reportMissingTypeStubs": false, "stubPath": "pyi", "pythonVersion": "3.11", "pythonPlatform": "Linux" } ``` -------------------------------- ### Intercept and Block Network Requests Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/network.md Demonstrates how to use context.route to intercept network traffic and abort requests based on URL patterns, such as blocking images or analytics scripts. ```typescript const context = await browser.newContext(); const page = await context.newPage(); // Block all images await context.route("**/*.{png,jpg,gif,svg}", (route) => route.abort()); // Block analytics await context.route("**/analytics/**", (route) => route.abort()); ``` -------------------------------- ### Screenshot and visual regression Source: https://github.com/theforgivenone/unibrowser/blob/main/skills/cross-browser-e2e/SKILL.md Capturing screenshots of pages or specific elements, including support for visual regression testing by comparing against baseline images. ```typescript const buffer = await page.screenshot({ fullPage: true }); await page.expectScreenshot("./screenshots/home.png"); ``` -------------------------------- ### Page navigation and element selection Source: https://github.com/theforgivenone/unibrowser/blob/main/skills/cross-browser-e2e/SKILL.md Methods for navigating between URLs and locating elements on a page using various strategies like CSS selectors, text, roles, and test IDs. ```typescript // Navigation await page.goto("https://example.com"); await page.reload(); // Locators const h1 = page.locator("h1"); const el = page.getByText("Click me"); const heading = page.getByRole("heading", { name: "Welcome" }); const input = page.getByLabel("Email"); const testEl = page.getByTestId("login-button"); ``` -------------------------------- ### Define Cross-Browser Test Suite Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/cross-browser.md Demonstrates the basic usage of crossBrowserSuite to run tests across multiple browser engines. It shows how to access the page and browser context within test callbacks. ```typescript import { crossBrowserSuite } from "unibrowser"; crossBrowserSuite("My Feature", (test) => { test("should work", async ({ page }) => { await page.goto("https://example.com"); await page.expectTitle("Example Domain"); }); }); ``` -------------------------------- ### Click an Element Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/element.md Simulates a click action on the element. Supports specifying which mouse button to use for the click. ```typescript await page.locator("button").click(); await page.locator("button").click({ button: "right" }); ``` -------------------------------- ### DELETE /close Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/unibrowser.md Closes the browser instance and all associated pages to free system resources. ```APIDOC ## DELETE /close ### Description Closes the browser and all pages. Should be called to prevent memory leaks. ### Method DELETE ### Response #### Success Response (200) - **status** (string) - Confirmation of closure. ``` -------------------------------- ### Fill Input Element with Text Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/element.md Types the provided text into an input or textarea element. This simulates user typing behavior. ```typescript await page.locator("input").type("hello"); ``` -------------------------------- ### Vitest Configuration for Unibrowser Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/cross-browser.md This snippet shows the basic Vitest configuration file (`vitest.config.ts`) for a Unibrowser project. It sets the test timeout and specifies the directory for test files. This configuration allows leveraging standard Vitest features for testing. ```typescript import { defineConfig } from "vitest/config"; export default defineConfig({ test: { testTimeout: 30000, include: ["tests/**/*.test.ts"], }, }); ``` -------------------------------- ### Manage Cookies in a Context Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/context.md Allows retrieval of all cookies within a context, setting specific cookies, and clearing all cookies. ```typescript const cookies = await context.cookies(); ``` ```typescript await context.addCookies([ { name: "session", value: "abc123", domain: "example.com", path: "/", }, ]); ``` ```typescript await context.clearCookies(); ``` -------------------------------- ### Network Routing and Manipulation Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/context.md Provides functionality to intercept network requests matching a URL pattern, allowing for actions like blocking, mocking responses, or modifying requests. It also supports removing routes and simulating offline mode. ```typescript // Block images await context.route("**/*.{png,jpg,gif}", (route) => route.abort()); // Mock API response await context.route("**/api/user", (route) => { route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ name: "Test User" }), }); }); // Modify request await context.route("**/api/**", (route) => { route.continue({ headers: { ...route.request().headers(), "X-Auth": "token" }, }); }); ``` ```typescript await context.unroute("**/api/**"); ``` ```typescript await context.setOffline(true); // ... test offline behavior ... await context.setOffline(false); ``` -------------------------------- ### Configure Browser Selection Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/cross-browser.md Shows how to restrict tests to specific browsers using the options object or global environment variables. ```typescript import { crossBrowserSuite } from "unibrowser"; crossBrowserSuite("Quick Test", (test) => { test("works", async ({ page }) => { await page.goto("https://example.com"); }); }, { browsers: ["chromium", "firefox"] }); ``` ```bash # Run only Chromium UNIBROWSER_BROWSERS=chromium npm run test:e2e # Run Chromium + Firefox (skip WebKit) UNIBROWSER_BROWSERS=chromium,firefox npm run test:e2e ``` -------------------------------- ### Caching Playwright Browsers in GitHub Actions Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/ci-cd.md This snippet shows how to cache Playwright browsers in GitHub Actions to speed up subsequent runs. It uses the 'actions/cache' action to store and retrieve the browser binaries based on the OS and a hash of the Playwright package file. ```yaml - name: Cache Playwright browsers uses: actions/cache@v4 id: playwright-cache with: path: ~/.cache/ms-playwright key: playwright-${{ runner.os }}-${{ hashFiles('node_modules/playwright/package.json') }} - name: Install browsers if: steps.playwright-cache.outputs.cache-hit != 'true' run: npx playwright install --with-deps chromium firefox webkit ``` -------------------------------- ### Perform screenshot and visual comparison Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/reference/utils.md Tools for capturing page screenshots, comparing image buffers pixel-by-pixel, and asserting page state against baseline images. ```typescript import { captureScreenshot, compareScreenshots, assertScreenshotMatches } from "unibrowser"; const buffer = await captureScreenshot(page.raw, { fullPage: true }); const result = await compareScreenshots(actualBuffer, expectedBuffer); console.log(result.diffPercent); await assertScreenshotMatches(page.raw, "./baseline.png", 0.1); ``` -------------------------------- ### Close a Browser Context Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/context.md Closes the current browser context and all pages associated with it. ```typescript await context.close(); ``` -------------------------------- ### Optimize Test Performance Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/cross-browser.md Configures Vitest to use a single thread to maximize browser pool efficiency and speed up E2E test execution. ```typescript import { defineConfig } from "vitest/config"; export default defineConfig({ test: { pool: "threads", poolOptions: { threads: { singleThread: true }, }, }, }); ``` -------------------------------- ### Setting WaitUntil Strategy for SPAs Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/reference/config.md Configures the navigation wait strategy to 'domcontentloaded', which is optimized for single-page applications compared to the default 'load' strategy. ```typescript const config = loadConfig({ waitUntil: "domcontentloaded", }); ``` -------------------------------- ### Manage application logging Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/reference/utils.md Utilities for retrieving, configuring, and creating logger instances to track application events with varying severity levels. ```typescript import { getLogger, setLogLevel, createLogger } from "unibrowser"; const log = getLogger(); log.info("Browser launched"); setLogLevel("debug"); const customLog = createLogger("debug"); customLog.debug("Custom logger debug message"); ``` -------------------------------- ### Navigation Goto Options Interface (TypeScript) Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/reference/types.md Defines the `GotoOptions` interface for configuring navigation actions. Options include `waitUntil` conditions, request `timeout`, and specifying a `referer` header. ```typescript interface GotoOptions { waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit"; timeout?: number; referer?: string; } ``` -------------------------------- ### Element interactions and state checks Source: https://github.com/theforgivenone/unibrowser/blob/main/skills/cross-browser-e2e/SKILL.md Common interactions such as clicking, typing, and checking elements, alongside methods to retrieve element states like visibility, text content, and attributes. ```typescript // Interactions await el.click(); await el.type("hello"); // State const visible = await el.isVisible(); const text = await el.innerText(); const href = await el.getAttribute("href"); ``` -------------------------------- ### Mock API Responses Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/network.md Shows how to intercept specific API endpoints and fulfill them with custom JSON responses, allowing for isolated frontend testing. ```typescript await context.route("**/api/user", (route) => { route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ name: "Test User", email: "test@example.com" }), }); }); ``` -------------------------------- ### Modify Request Headers Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/guides/network.md Illustrates how to intercept requests and continue them with modified headers, useful for injecting authentication tokens. ```typescript await context.route("**/api/**", (route) => { route.continue({ headers: { ...route.request().headers(), "Authorization": "Bearer test-token", }, }); }); ``` -------------------------------- ### Find Elements by ARIA Role Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/element.md Finds elements within a scoped locator based on their ARIA role. This is a robust method for accessibility-aware element selection. ```typescript const form = page.locator("#login"); const heading = form.getByRole("heading", { name: "Sign in" }); const button = form.getByRole("button", { name: "Submit" }); ``` -------------------------------- ### Define cross-browser test suite Source: https://github.com/theforgivenone/unibrowser/blob/main/skills/cross-browser-e2e/SKILL.md Basic structure for creating a test suite that executes across all supported browsers using the crossBrowserSuite function. ```typescript import { expect } from "vitest"; import { crossBrowserSuite } from "unibrowser"; crossBrowserSuite("My Feature", (test) => { test("should load the page", async ({ page }) => { await page.goto("https://example.com"); await page.expectTitle("Example Domain"); }); }); ``` -------------------------------- ### Run Cross-Browser E2E Tests with unibrowser (TypeScript) Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/README.md This snippet demonstrates how to write and run end-to-end tests across multiple browsers using unibrowser. It utilizes the `crossBrowserSuite` function to define a test suite that will be executed on Chromium, Firefox, and WebKit. The tests involve navigating to a URL and asserting the page title and element text. Dependencies include 'vitest' for testing and 'unibrowser' for cross-browser capabilities. ```typescript import { expect } from "vitest"; import { crossBrowserSuite } from "unibrowser"; crossBrowserSuite("My App", (test) => { test("loads homepage", async ({ page }) => { await page.goto("https://example.com"); await page.expectTitle("Example Domain"); const h1 = page.locator("h1"); await h1.expectText("Example Domain"); }); }); ``` -------------------------------- ### Check a Checkbox or Radio Button Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/element.md Simulates checking a checkbox or selecting a radio button. This is a common interaction for form elements. ```typescript await page.locator('input[type="checkbox"]').check(); ``` -------------------------------- ### Assert Element Text (Exact Match) Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/element.md Asserts that the innerText of an element exactly matches the expected string after trimming whitespace. This is useful for verifying precise text content. ```typescript await page.locator("h1").expectText("Welcome"); ``` -------------------------------- ### Select Option in a Select Element Source: https://github.com/theforgivenone/unibrowser/blob/main/docs/api/element.md Selects one or more options from a `