### Parameterize Custom Playwright Fixtures Source: https://github.com/checkly/playwright-examples/blob/main/README.md Demonstrates how to create and parameterize custom fixtures in Playwright, allowing for flexible test setup and data injection. This pattern is useful for customizing test environments or data inputs. ```TypeScript import { test as base, expect } from '@playwright/test'; // Define a fixture with parameters const testWithParam = base.extend({ user: async ({}, use) => { // In a real scenario, this might fetch user data based on a parameter const userData = { name: 'Test User', id: 123 }; await use(userData); }, }); test('Use parameterized fixture', async ({ user }) => { console.log(`Testing with user: ${user.name}`); expect(user.id).toBe(123); }); ``` -------------------------------- ### Use Custom Playwright Fixtures for Reusability Source: https://github.com/checkly/playwright-examples/blob/main/README.md Explains the benefits and implementation of custom Playwright fixtures to promote code reusability and maintainability. Fixtures abstract common setup and teardown logic, making tests cleaner. ```TypeScript import { test as base, expect } from '@playwright/test'; // Define a custom fixture for authenticated page access const testWithAuth = base.extend({ authPage: async ({ page }, use) => { // Login process await page.goto('/login'); await page.fill('#username', 'testuser'); await page.fill('#password', 'password'); await page.click('button[type="submit"]'); await expect(page).toHaveURL('/dashboard'); // Provide the authenticated page to the test await use(page); }, }); test('Test dashboard page with authenticated fixture', async ({ authPage }) => { // authPage is already logged in await expect(authPage.locator('h1')).toContainText('Welcome'); }); ``` -------------------------------- ### Add Global beforeEach and afterEach Hooks in Playwright Source: https://github.com/checkly/playwright-examples/blob/main/README.md Illustrates how to implement global `beforeEach` and `afterEach` hooks in Playwright tests. These hooks are executed before and after each test case, respectively, useful for setup and teardown operations. ```TypeScript import { test, expect } from '@playwright/test'; // Global beforeEach hook test.beforeEach(async ({ page }) => { console.log('Executing global beforeEach hook...'); // Example: Navigate to a common page or set up common data // await page.goto('https://example.com/login'); // await page.fill('#username', 'testuser'); // await page.fill('#password', 'password'); // await page.click('button[type="submit"]'); // await expect(page).toHaveURL('/dashboard'); }); // Global afterEach hook test.afterEach(async ({ page }) => { console.log('Executing global afterEach hook...'); // Example: Take a screenshot on failure or clean up resources // if (testInfo.status === 'failed') { // await page.screenshot({ path: `screenshots/${testInfo.title}.png` }); // } }); test('Example test using global hooks', async ({ page }) => { console.log('Running the actual test...'); await expect(page.locator('body')).toBeVisible(); }); ``` -------------------------------- ### Add Type Checking and Linting to Playwright Project Source: https://github.com/checkly/playwright-examples/blob/main/README.md Demonstrates how to integrate type checking and linting tools into a Playwright project for improved code quality and maintainability. This setup helps catch errors early in the development cycle. ```TypeScript // Code for type checking and linting setup would go here. // This might include tsconfig.json, ESLint configuration, and Playwright configuration. console.log('Setting up type checking and linting...'); ``` -------------------------------- ### Apply Playwright Test Steps with TypeScript Decorators Source: https://github.com/checkly/playwright-examples/blob/main/README.md Showcases the use of TypeScript decorators to define and apply Playwright test steps, offering a more declarative and organized way to structure test logic. This enhances readability and reusability. ```TypeScript import { test, expect } from '@playwright/test'; // Example decorator (conceptual) function step(description: string) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = async function (...args: any[]) { console.log(`Starting step: ${description}`); await originalMethod.apply(this, args); console.log(`Finished step: ${description}`); }; return descriptor; }; } class MyTest { @step('Navigate to homepage') async navigate() { // await page.goto('/'); } @step('Fill login form') async login(username: string, password: string) { // await page.fill('#username', username); // await page.fill('#password', password); // await page.click('button[type="submit"]'); } } test('Login test with decorators', async ({ page }) => { const testInstance = new MyTest(); await testInstance.navigate(); await testInstance.login('user', 'pass'); await expect(page).toHaveURL('/dashboard'); }); ``` -------------------------------- ### Speed Up Playwright Tests with Shared StorageState Source: https://github.com/checkly/playwright-examples/blob/main/README.md Explains how to leverage Playwright's `storageState` feature to speed up test execution by persisting authentication states. This avoids repetitive login steps in subsequent tests. ```TypeScript // Example of saving storage state after login // await page.context().storageState({ path: 'state.json' }); // Example of loading storage state for subsequent tests // await page.context().storageState({ path: 'state.json' }); console.log('Using storageState for faster tests...'); ``` -------------------------------- ### Validate API Response Schema with Playwright Source: https://github.com/checkly/playwright-examples/blob/main/README.md Demonstrates how to use Playwright to make API requests and validate the structure and data types of the JSON response against a predefined schema. This ensures API consistency and correctness. ```APIDOC APIDOC: Endpoint: GET /users/{id} Description: Retrieves user details by ID. Parameters: - name: id in: path required: true schema: type: integer description: The ID of the user to retrieve. Responses: 200 OK: description: User details. content: application/json: schema: type: object properties: id: type: integer description: Unique identifier for the user. name: type: string description: The name of the user. email: type: string format: email description: The email address of the user. required: - id - name - email 404 Not Found: description: User not found. Playwright Example: import { test, expect } from '@playwright/test'; test('Validate user API response schema', async ({ page }) => { const userId = 1; const response = await page.request.get(`/users/${userId}`); // Assuming base URL is configured expect(response.ok()).toBeTruthy(); const responseBody = await response.json(); // Schema validation using expect assertions (or a library like Ajv) expect(responseBody).toHaveProperty('id'); expect(typeof responseBody.id).toBe('number'); expect(responseBody.id).toBe(userId); expect(responseBody).toHaveProperty('name'); expect(typeof responseBody.name).toBe('string'); expect(responseBody).toHaveProperty('email'); expect(typeof responseBody.email).toBe('string'); expect(responseBody.email).toMatch(/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/); // Check for required properties expect(responseBody).not.toHaveProperty('password'); // Assuming password is not returned }); ``` -------------------------------- ### Detect Broken Links with Playwright Source: https://github.com/checkly/playwright-examples/blob/main/README.md Provides a method to identify broken links (e.g., 404 errors) within a web page using Playwright. This script scans all anchor tags and checks their response status. ```TypeScript import { test, expect } from '@playwright/test'; test('Detect broken links', async ({ page }) => { await page.goto('https://example.com'); // Replace with target URL const links = await page.$$eval('a', anchors => anchors.map(a => a.href)); for (const link of links) { if (!link || link.startsWith('mailto:') || link.startsWith('tel:')) { continue; } try { const response = await page.request.get(link, { failOnStatusCode: false }); if (response.status() >= 400) { console.warn(`Broken link found: ${link} (Status: ${response.status()})`); // Optionally, fail the test or collect broken links // await expect(response.ok()).toBe(true); } } catch (error) { console.error(`Error checking link ${link}: ${error.message}`); // Optionally, fail the test or collect errors // await expect(true).toBe(false); } } }); ``` -------------------------------- ### Control Time Zones and Timeouts in Playwright Source: https://github.com/checkly/playwright-examples/blob/main/README.md Explains how to configure time zones and various timeout settings within Playwright tests. This is crucial for testing applications that behave differently based on location or for managing test execution duration. ```TypeScript import { test, expect } from '@playwright/test'; test.use({ // Set a specific timezone for the browser context timezoneId: 'America/New_York', // Set a default navigation timeout navigationTimeout: 60000, // 60 seconds // Set a default action timeout actionTimeout: 10000, // 10 seconds }); test('Test with custom timezone and timeouts', async ({ page }) => { // The page context will now operate with the specified timezone // await page.goto('https://example.com'); console.log('Browser context configured with timezone and timeouts.'); await expect(page).toHaveTitle(/Playwright/); }); ``` -------------------------------- ### Automatically Catch Failed HTTP Requests in Playwright Tests Source: https://github.com/checkly/playwright-examples/blob/main/README.md Demonstrates how to monitor network activity during Playwright tests to automatically detect and report failed HTTP requests (e.g., 4xx or 5xx errors). This proactive approach helps identify backend issues early. ```TypeScript import { test, expect } from '@playwright/test'; test.describe('Network Monitoring', () => { let failedRequests: string[] = []; test.beforeEach(async ({ page }) => { failedRequests = []; // Reset for each test page.on('response', async (response) => { const status = response.status(); if (status >= 400) { const url = response.url(); console.warn(`Failed request: ${url} - Status: ${status}`); failedRequests.push(`${url} - ${status}`); } }); }); test('should not have failed HTTP requests', async ({ page }) => { await page.goto('https://example.com'); // Navigate to a page that might trigger requests // Perform actions that trigger network requests // await page.click('button'); // Assert that no failed requests were captured expect(failedRequests).toEqual([]); }); // Add more tests that might trigger different network scenarios }); ``` -------------------------------- ### Display Dynamic Date with Relative Time Source: https://github.com/checkly/playwright-examples/blob/main/controlling-time/demo/timezone.html This JavaScript code snippet imports the @github/relative-time-element library and dynamically updates an HTML element with a formatted date. It also sets up the element to display time relative to the current moment. Dependencies include the @github/relative-time-element library. It targets a specific HTML structure for rendering. ```JavaScript import githubrelativeTimeElement from "https://cdn.jsdelivr.net/npm/@github/relative-time-element@4.4.3/+esm" const date = new Date(Date.UTC(2024, 9, 25, 14)) const dateString = new Intl.DateTimeFormat("en-US", { dateStyle: "full", timeStyle: "short", }).format(date) document.querySelector(".container").innerHTML = `

⛰️πŸ₯ΎπŸŽ‰πŸ‘«πŸŽ‰πŸ₯Ύβ›°οΈ

${dateString}

${date.toISOString()} ` ``` -------------------------------- ### JavaScript Session Timer with Relative Time Source: https://github.com/checkly/playwright-examples/blob/main/controlling-time/demo/index.html Implements a session timer that disables a button, displays a countdown using a relative time element, and resets after a timeout. It utilizes the `@github/relative-time-element` library for displaying elapsed time and manages session state through button disabling and message updates. ```javascript import githubrelativeTimeElement from "https://cdn.jsdelivr.net/npm/@github/relative-time-element@4.4.3/+esm" const TIMEOUT = 300_000; const button = document.querySelector("button"); button.addEventListener("click", () => { button.disabled = true; document.querySelector("#result").innerHTML = `

Session ends in .

`; setTimeout(() => { button.disabled = false; document.querySelector("#result").innerHTML = "

Session is over.

"; }, TIMEOUT); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.