Playwright TypeScript Test Rules

Playwright TypeScript Test Rules

Sets rules for generating Playwright TypeScript tests: role-based locators, web-first assertions, test structure, naming and file organisation.


description: 'Playwright test generation instructions'
applyTo: '/tests//.ts, /e2e//.ts, /playwright//*.ts, **/playwright.config.ts'


Test Writing Guidelines

Use these guidelines for the Playwright suite identified by its configured testDir and testMatch, including its fixtures and page objects. Keep unrelated application code and other test frameworks outside this scope; adapt the instruction glob if the suite uses a custom location. See [Playwright test configuration](https://playwright.dev/docs/test-configuration).

Code Quality Standards

  • Locators: Prioritize user-facing, role-based locators (getByRole, getByLabel, getByText, etc.) for resilience and accessibility. Use test.step() to group interactions and improve test readability and reporting.
  • Assertions: Use auto-retrying web-first assertions. These assertions start with the await keyword (e.g., await expect(locator).toHaveText()). Avoid expect(locator).toBeVisible() unless specifically testing for visibility changes.
  • Timeouts: Rely on Playwright's built-in auto-waiting mechanisms. Avoid hard-coded waits or increased default timeouts.
  • Clarity: Use descriptive test and step titles that clearly state the intent. Add comments only to explain complex logic or non-obvious interactions.

Test Structure

  • Imports: Start with import { test, expect } from '@playwright/test';.
  • Organization: Group related tests for a feature under a test.describe() block.
  • Hooks: Use beforeEach for setup actions common to all tests in a describe block (e.g., navigating to a page).
  • Titles: Follow a clear naming convention, such as Feature - Specific action or scenario.

File Organization

  • Location: Store specs, fixtures, and page objects in the existing Playwright suite. Put specs under the configured testDir and ensure they match testMatch, including projects using e2e/ or another directory.
  • Naming: Follow the suite's configured matcher and existing naming convention; use <feature-or-page>.spec.ts when that matcher accepts it.
  • Scope: Aim for one test file per major application feature or page.

Assertion Best Practices

  • UI Structure: Use toMatchAriaSnapshot to verify the accessibility tree structure of a component. This provides a comprehensive and accessible snapshot.
  • Element Counts: Use toHaveCount to assert the number of elements found by a locator.
  • Text Content: Use toHaveText for exact text matches and toContainText for partial matches.
  • Navigation: Use toHaveURL to verify the page URL after an action.

Example Test Structure

import { test, expect } from '@playwright/test';

test.describe('Movie Search Feature', () => {
  test.beforeEach(async ({ page }) => {
    // Navigate to the application before each test
    await page.goto('https://debs-obrien.github.io/playwright-movies-app');
  });

  test('Search for a movie by title', async ({ page }) => {
    await test.step('Activate and perform search', async () => {
      await page.getByRole('search').click();
      const searchInput = page.getByRole('textbox', { name: 'Search Input' });
      await searchInput.fill('Garfield');
      await searchInput.press('Enter');
    });

    await test.step('Verify search results', async () => {
      // Verify the accessibility tree of the search results
      await expect(page.getByRole('main')).toMatchAriaSnapshot(`
        - main:
          - heading "Garfield" [level=1]
          - heading "search results" [level=2]
          - list "movies":
            - listitem "movie":
              - link "poster of The Garfield Movie The Garfield Movie rating":
                - /url: /playwright-movies-app/movie?id=tt5779228&page=1
                - img "poster of The Garfield Movie"
                - heading "The Garfield Movie" [level=2]
      `);
    });
  });
});

Test Execution Strategy

  1. Initial Run: Use the project's Playwright test command and configured projects; npx playwright test --project=chromium applies when the configuration defines that project.
  2. Debug Failures: Analyze test failures and identify root causes
  3. Iterate: Refine locators, assertions, or test logic as needed
  4. Validate: Ensure tests pass consistently and cover the intended functionality
  5. Report: Provide feedback on test results and any issues discovered

Quality Checklist

Before finalizing tests, ensure:

  • [ ] All locators are accessible and specific and avoid strict mode violations
  • [ ] Tests are grouped logically and follow a clear structure
  • [ ] Assertions are meaningful and reflect user expectations
  • [ ] Tests follow consistent naming conventions
  • [ ] Code is properly formatted and commented

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 13,411 prompts

More by @OpenSourceBuffGuy

See all
Running Man Pulled Back by Semi Chibi Double prompt image

Running Man Pulled Back by Semi Chibi Double

Makes a bright studio editorial photo of a running person from a reference photo, with a 3D semi-chibi double tugging their clothes back and realistic fabric tension.

image-prompt, gpt-image, reference-image, face-reference, negative-prompt, photorealistic, editorial, chibi, 3d-render, studio-lighting, white-background, fashion, portrait, full-body, motion-blur, whimsical, vertical-format, character-consistency, action-figure, fashion-shoot, pixar-style, soft-lighting, for-photographers, for-artists, humorous

Cornflower meadow path to a misty sailboat prompt image

Cornflower meadow path to a misty sailboat

Draws a portrait-format colored-pencil scene of a cornflower meadow with a winding path leading to a misty sea, a distant sailboat and a sunset sky.

image-prompt, illustration, landscape, flowers, ocean, dreamy, pastel, golden-hour, vertical-format, nano-banana, sketch, summer, for-artists, wallpaper, soft-lighting, wide-shot, high-angle

Swordswoman faces colossal robed figure in industrial yard prompt image

Swordswoman faces colossal robed figure in industrial yard

Writes a two-scene, 20-second live-action video prompt in which a swordswoman freezes a colossal figure with realistic ice and shatters him with a finishing slash.

video-prompt, seedance, action, martial-arts, visual-effects, multi-shot, cinematic, character-consistency, timed-beats, negative-prompt, guardrails, structured-output, photorealistic, fantasy-world, japan, camera-movement, slow-motion, blue-hour, widescreen, advanced, long-form, for-filmmakers, sound-effects, creatures, warriors

Reviews

Loading reviews…

Discussion

Loading comments…