Reusable utilities for Playwright test automation - page helpers, generators, string utilities, and more
npm install playwright-utils-liteReusable utilities for Playwright test automation - page helpers, generators, string utilities, and more.
``bash`
npm install playwright-utils-lite
Note: @playwright/test is a peer dependency and must be installed separately if you want to use the Playwright helpers.
`bash`
npm install @playwright/test
- Playwright Helpers - Page interaction, waiting, scrolling, network, and viewport utilities
- Data Generators - Random values, passwords, phone numbers, emails, addresses, credit cards, dates
- String Utilities - Normalization, HTML processing, regex builders, formatting
- File Utilities - CSV reading/writing, file download waiting
`typescript
// Import everything
import { PageHelpers, generatePassword, normalize } from 'playwright-utils-lite';
// Or import specific modules
import { PageHelpers, WaitHelpers } from 'playwright-utils-lite/playwright';
import { generateEmail, generatePhone } from 'playwright-utils-lite/generators';
import { stripHtml, escapeRegex } from 'playwright-utils-lite/string';
import { readCSV, waitForDownload } from 'playwright-utils-lite/file';
`
#### Page Helpers
`typescript
import { createPageHelpers } from 'playwright-utils-lite/playwright';
test('example test', async ({ page }) => {
const helpers = createPageHelpers(page);
// Viewport detection
if (helpers.isMobile) {
console.log('Running on mobile viewport');
}
// Safe interactions (returns boolean success)
const clicked = await helpers.clickSafe(page.locator('#submit'));
const filled = await helpers.fillSafe(page.locator('#email'), 'test@example.com');
// Get text safely with fallback
const text = await helpers.getTextSafe(page.locator('.price'), '$0.00');
// Get all visible elements
const visibleItems = await helpers.getAllVisibleElements(page.locator('.item'));
});
`
#### Wait Helpers
`typescript
import { createWaitHelpers } from 'playwright-utils-lite/playwright';
test('wait example', async ({ page }) => {
const waits = createWaitHelpers(page);
// Wait for element states
await waits.waitForVisible(page.locator('.modal'));
await waits.waitForHidden(page.locator('.loading'));
// Wait for custom conditions
await waits.waitForCondition(
async () => (await page.locator('.items').count()) > 5,
{ timeout: 10000, message: 'Expected more than 5 items' }
);
// Wait for text
await waits.waitForText(page.locator('.status'), 'Complete');
// Wait for loading indicators to disappear
await waits.waitForLoadingGone('.spinner');
});
`
#### Scroll Helpers
`typescript
import { createScrollHelpers } from 'playwright-utils-lite/playwright';
test('scroll example', async ({ page }) => {
const scroll = createScrollHelpers(page);
// Basic scrolling
await scroll.scrollToElement(page.locator('#footer'));
await scroll.scrollToTop();
await scroll.scrollToBottom();
// Scroll + action combinations
await scroll.clickWithScroll(page.locator('#hidden-button'));
await scroll.fillWithScroll(page.locator('#form-field'), 'value');
// Lazy loading - scroll to load all content
await scroll.scrollToLoadAll({ delay: 500, maxScrolls: 20 });
// Scroll until element is found
const found = await scroll.scrollUntilFound(page.locator('.target-item'));
});
`
#### Network Helpers
`typescript
import { createNetworkHelpers } from 'playwright-utils-lite/playwright';
test('network example', async ({ page, context }) => {
const network = createNetworkHelpers(page, context);
// Make API calls using page context (shares cookies)
const data = await network.fetchJson<{ items: string[] }>('/api/items');
await network.postJson('/api/submit', { name: 'Test' });
// Cookie management
const token = await network.getCookie('auth_token');
await network.setCookie('preference', 'dark', { path: '/' });
// Mock responses
await network.mockResponse('**/api/users', {
status: 200,
body: { users: [] },
});
// Block requests
await network.blockResourceTypes(['image', 'font']);
// Local storage
await network.setLocalStorageItem('theme', 'dark');
});
`
#### Viewport Helpers
`typescript
import { createViewportHelpers } from 'playwright-utils-lite/playwright';
test('viewport example', async ({ page }) => {
const viewport = createViewportHelpers(page);
// Set device viewport
await viewport.setDevice('iPhone 14');
await viewport.setDevice('Desktop FHD');
// Check current viewport
if (viewport.isMobile()) {
// Mobile-specific assertions
}
// Test at multiple viewports
await viewport.testResponsive(async (isMobile) => {
// Test runs for both mobile and desktop
});
});
`
#### Random Values
`typescript
import {
randomInt,
randomString,
randomElement,
shuffle,
randomUUID,
} from 'playwright-utils-lite/generators';
const id = randomInt(1, 1000); // Random integer
const code = randomString(8); // Random alphanumeric string
const item = randomElement(['a', 'b']); // Random array element
const shuffled = shuffle([1, 2, 3, 4]); // Shuffled array
const uuid = randomUUID(); // UUID v4
`
#### Password Generator
`typescript
import {
generatePassword,
generateSecurePassword,
generatePin,
validatePasswordStrength,
} from 'playwright-utils-lite/generators';
// Basic password
const password = generatePassword({ length: 12 });
// Secure password with all character types
const secure = generateSecurePassword(16);
// PIN code
const pin = generatePin(6);
// Validate strength
const strength = validatePasswordStrength('MyP@ssw0rd');
console.log(strength.level); // 'strong'
`
#### Phone Generator
`typescript
import {
generatePhone,
formatPhone,
isValidPhone,
} from 'playwright-utils-lite/generators';
// Generate phone number
const phone = generatePhone({ country: 'US', format: 'dashed' });
// Output: "201-555-1234"
// Format existing number
const formatted = formatPhone('2015551234', 'international');
// Output: "+1 201 555 1234"
// Validate
const valid = isValidPhone('201-555-1234', 'US'); // true
`
#### Email Generator
`typescript
import {
generateEmail,
generateTimestampedEmail,
generateProfessionalEmail,
} from 'playwright-utils-lite/generators';
// Basic email with timestamp
const email = generateEmail({
prefix: 'test',
domain: 'mailinator.com',
});
// Output: "test_20240115_143022@mailinator.com"
// Quick timestamped email
const quick = generateTimestampedEmail('qa', 'test.com');
// Professional looking email
const pro = generateProfessionalEmail('John', 'Doe', 'company.com');
// Output: "john.doe@company.com"
`
#### Address Generator
`typescript
import {
generateFullAddress,
generateStreetAddress,
generatePostalCode,
} from 'playwright-utils-lite/generators';
// Full address
const address = generateFullAddress({ country: 'US', includeApt: true });
// {
// street: "123 Oak Street",
// apt: "Apt 4B",
// city: "New York",
// state: "NY",
// postalCode: "10001",
// country: "US"
// }
// Canadian postal code
const postalCode = generatePostalCode('CA');
// Output: "M5V 2H1"
`
#### Credit Card Generator
`typescript
import {
generateCard,
generateCardNumber,
isValidCardNumber,
getTestCardNumber,
} from 'playwright-utils-lite/generators';
// Generate complete card
const card = generateCard({ type: 'visa' });
// {
// number: "4111111111111111",
// expiry: "03/27",
// cvc: "123",
// type: "visa"
// }
// Test card for specific scenarios
const testCard = getTestCardNumber('success');
const declineCard = getTestCardNumber('decline');
// Validate card number (Luhn check)
const valid = isValidCardNumber('4111111111111111'); // true
`
#### Date Utilities
`typescript
import {
formatDate,
addDays,
addInterval,
futureDate,
randomBirthDate,
diffInBusinessDays,
} from 'playwright-utils-lite/generators';
// Format date
const formatted = formatDate(new Date(), 'MM/DD/YYYY');
// Add time
const nextWeek = addDays(new Date(), 7);
const nextMonth = addInterval(new Date(), '1m');
// Future date
const delivery = futureDate(5); // 5 days from now
// Random birth date (18-65 years old)
const birthDate = randomBirthDate(18, 65);
// Business days between dates
const workDays = diffInBusinessDays(startDate, endDate);
`
`typescript
import {
// Normalization
normalize,
toSlug,
toCamelCase,
normalizeWhitespace,
// HTML
stripHtml,
escapeHtml,
extractLinks,
// Regex
escapeRegex,
buildFlexibleRegex,
PATTERNS,
// Formatting
formatCurrency,
truncate,
capitalize,
mask,
} from 'playwright-utils-lite/string';
// Normalize
const clean = normalizeWhitespace(' hello world '); // "hello world"
const slug = toSlug('Hello World!'); // "hello-world"
const camel = toCamelCase('hello-world'); // "helloWorld"
// HTML
const text = stripHtml('
Hello World
'); // "Hello World"