Playwright Documentation

repository·main·Indexed 41 days ago

https://github.com/microsoft/playwright.dev

Official documentation for Playwright, including guides, API references, and the playwright-cli for browser attachment, test generation, and locator authoring.

Tokens
233.3K
Snippets
877
Records
1K
Agent score
49%

What's inside Playwright

  1. Introduction to API testing with Playwright

    main

    Playwright allows you to interact directly with your application's REST API using the APIRequestContext class. This enables you to perform server-side operations without the overhead of loading a web page or executing JavaScript in a browser context.

    Common use cases for API testing include:

    • Testing your server's API endpoints directly.
    • Preparing server-side state (e.g., seeding data) before a browser-based test begins.
    • Validating server-side post-conditions (e.g., checking if a database record was created) after performing actions in the browser.
  2. Explore Playwright Trace Viewer features

    main

    The Playwright Trace Viewer provides a comprehensive interface for debugging tests by visualizing actions, snapshots, and logs. Key features include:

    • Actions Tab: View the locator used for every action, its duration, and the corresponding DOM snapshot. You can use 'Before' and 'After' tabs to see the state change.
    • Screenshots: A film strip (screencast) allows you to visually navigate through the test execution. Hovering over the film strip provides a magnified view.
    • Snapshots: If enabled, Playwright captures complete DOM snapshots for each action. Snapshots are categorized as:
      • Before: At the time the action is called.
      • Action: At the moment of the performed input (useful for seeing exact click positions).
      • After: After the action completes.
    • Source: Highlights the specific line of code in your test file corresponding to the selected action.
    • Call: Displays metadata about the action, such as duration, the locator used, strict mode status, and keys used.
    • Log: Provides a detailed execution log of Playwright's internal operations (e.g., scrolling, waiting for visibility, stability).
    • Errors: Displays error messages and highlights the failure point on the timeline and in the source code.
    • Console: Shows logs from both the browser and the test file. You can filter these logs by selecting a specific action or a time range on the timeline.
    • Network: Displays all network requests made during the test. You can sort by method, status, duration, etc., and inspect headers and bodies. Filtering is available via the timeline or by selecting an action.
    • Metadata: Shows test environment details like browser type, viewport size, and total duration.
  3. What is installed with Playwright

    main

    A standard Playwright installation creates the following project structure:

    • playwright.config.ts: Centralized test configuration for target browsers, timeouts, retries, projects, and reporters.
    • package.json & lockfile: Project dependencies.
    • tests/: A directory containing your test files (includes example.spec.ts by default).
  4. What is a BrowserContext and how to use it

    main

    A BrowserContext represents an isolated, independent browser session. It allows you to run multiple sessions in parallel without them sharing state (like cookies or local storage).

    Key characteristics:

    • Isolation: Each context is independent. If a page opens a popup via window.open, that popup belongs to the same BrowserContext as the parent page.
    • Non-persistence: Using browser.newContext() creates a non-persistent context that does not write browsing data to disk (similar to an incognito window).

    To use a context, create it from a Browser instance, open pages within it, and close the context when finished to clean up resources.

    // Create a new incognito browser context
    const context = await browser.newContext();
    
    // Create a new page inside context.
    const page = await context.newPage();
    await page.goto('https://example.com');
    
    // Dispose context once it's no longer needed.
    await context.close();
  5. What is Playwright MCP

    main

    Playwright MCP is a Model Context Protocol (MCP) server that enables Large Language Models (LLMs) to perform browser automation. Instead of relying on vision models or pixel coordinates, it uses structured accessibility snapshots.

    How it works:

    1. The LLM requests a browser_snapshot.
    2. The server returns an accessibility tree where every interactive element is assigned a unique reference (e.g., e5).
    3. The LLM uses these references as the target parameter in subsequent tool calls (like browser_click or browser_type) to interact with the page deterministically.
  6. What is component testing in Playwright?

    main

    Playwright component testing allows you to test web components in isolation by running regular Playwright end-to-end tests against a story gallery page served by your own development server.

    Unlike previous experimental packages, this approach is framework-agnostic and uses your existing build pipeline (Vite, Webpack, Next.js, etc.). It relies on the fixtures.mount() fixture from @playwright/test to drive the tests.

    Key Benefits:

    • Real Browser Environment: Tests run in Node.js while components run in a real browser, enabling real clicks, layout execution, and visual regression.
    • Pipeline Ownership: You use your own dev server, plugins, aliases, and CSS.
    • Stability: Uses standard @playwright/test imports and documented fixtures without needing experimental framework-specific packages.
    import { test, expect } from '@playwright/test';
    
    test('click should expand', async ({ mount }) => {
      const component = await mount('components/Expandable/Stateful');
      await component.getByRole('button').click();
      await expect(component.getByTestId('expanded')).toHaveValue('true');
    });
  7. Understand Playwright fixture execution order

    main

    Fixtures follow a specific lifecycle involving a setup phase, an await use() call, and a teardown phase. The execution order is governed by these rules:

    • Dependency Order: If fixture A depends on fixture B, B is always set up before A and torn down after A.
    • Lazy Execution: Non-automatic fixtures are executed lazily, meaning they are only set up when a test or hook explicitly requests them.
    • Scoping:
      • Test-scoped fixtures are torn down after each individual test.
      • Worker-scoped fixtures are torn down only when the worker process executing the tests is shut down.
    • Automatic Fixtures: Automatic fixtures (auto: true) are set up before tests and hooks. Automatic worker fixtures are set up before anything else, while automatic test fixtures are set up before tests and beforeEach hooks.
    import { test as base } from '@playwright/test';
    
    const test = base.extend<{ 
      testFixture: string, 
      autoTestFixture: string 
    }, {
      workerFixture: string,
      autoWorkerFixture: string
    }>({
      // Worker-scoped fixture
      workerFixture: [async ({ browser }) => {
        // setup
        await use('workerFixture');
        // teardown
      }, { scope: 'worker' }],
    
      // Automatic worker-scoped fixture
      autoWorkerFixture: [async ({ browser }) => {
        await use('autoWorkerFixture');
      }, { scope: 'worker', auto: true }],
    
      // Test-scoped fixture
      testFixture: [async ({ page, workerFixture }) => {
        await use('testFixture');
      }, { scope: 'test' }],
    
      // Automatic test-scoped fixture
      autoTestFixture: [async () => {
        await use('autoTestFixture');
      }, { scope: 'test', auto: true }],
    });
  8. Use APIRequestContext for REST API testing in Python

    main

    Playwright's APIRequestContext allows you to interact directly with a REST API without loading a web page or executing JavaScript in a browser. This is useful for:

    • Testing your server's API directly.
    • Preparing server-side state (e.g., creating users or data) before running browser-based tests.
    • Validating server-side post-conditions after performing actions in the browser.

    When using pytest-playwright, the api_request_context fixture is available to provide an instance of APIRequestContext.

    # Example of using the fixture in a test
    def test_api_call(api_request_context: APIRequestContext):
        response = api_request_context.get('/endpoint')
        assert response.ok
  9. How to use CDPSession to interact with Chrome DevTools Protocol

    main

    The CDPSession class allows you to communicate directly with the Chrome DevTools Protocol (CDP). This is useful for accessing low-level browser features not exposed by the standard Playwright API.

    To use it:

    1. Create a new session from a BrowserContext using newCDPSession(page).
    2. Use session.send(method, params) to call protocol methods.
    3. Use session.on(eventName, callback) to subscribe to protocol events.

    Refer to the DevTools Protocol Viewer for a full list of available methods and events.

    const client = await page.context().newCDPSession(page);
    await client.send('Animation.enable');
    client0.on('Animation.animationCreated', () => console.log('Animation created!'));
    const response = await client.send('Animation.getPlaybackRate');
    console.log('playback rate is ' + response.playbackRate);
    await client.send('Animation.setPlaybackRate', {
      playbackRate: response.playbackRate / 2
    });
  10. The playwright-cli core workflow

    main

    The playwright-cli operates on a continuous loop of state observation and interaction:

    1. Open: Use playwright-cli open <url> to initialize a session.
    2. Snapshot: Every command triggers a snapshot that returns an accessibility tree with element refs.
    3. Interact: Use the returned element refs to perform actions like click, type, or fill.
    4. Re-snapshot: Each interaction generates a new snapshot with updated state and new refs.

    Optimization Tip: For large pages, use the find command instead of a full snapshot if you only need to locate a single element. This is computationally cheaper.

    playwright-cli find "Sign in"
    playwright-cli find --regex "/sign (in|up)/i"