playwright-clipboard-testing
v0.9.1
Published
Playwright fixture and custom matchers for clipboard testing and assertions.
Maintainers
Readme
Playwright Clipboard Testing
Effortless clipboard testing for Playwright. Features custom fixtures, smart polling matchers, and auto-managed permissions.
Why?
Testing the Clipboard API in Playwright usually requires boilerplate code to manually grant clipboard-read and clipboard-write permissions for every context, write custom page functions, or deal with tricky async polling issues.
playwright-clipboard-testing simplifies this with:
- 🔌 Zero configuration — Chromium permissions are granted automatically under the hood (Firefox requires a 1-line config setup).
- 🔄 Built-in Auto-retries & Polling — Uses Playwright's native
expectpolling to wait until the clipboard updates asynchronously. - 📦 TypeScript Ready — Full type safety for JSON objects with
readJSON<T>()andwriteJSON<T>().
Table of Contents
Installation
Install as one of your dev dependencies:
npm install --save-dev playwright-clipboard-testingBrowser Support
Clipboard API testing is currently supported in Chromium-based and Firefox browsers.
Note: Permissions are auto-managed out of the box for Chromium. Firefox requires a one-time preference setup in your config.
If your Playwright setup runs tests in WebKit, you can skip clipboard tests for that browser:
test('should copy text to clipboard', async ({ page, clipboard, browserName }) => {
test.skip(browserName === 'webkit', 'Clipboard API is only supported in Chromium and Firefox');
// test logic...
});If your Playwright setup runs tests in Firefox, manually configure firefoxUserPrefs in your Playwright config:
import { defineConfig, devices } from '@playwright/test';
import { firefoxClipboardPrefs } from 'playwright-clipboard-testing/constants';
export default defineConfig({
projects: [
{
name: 'firefox',
use: {
...devices['Desktop Firefox'],
launchOptions: {
firefoxUserPrefs: firefoxClipboardPrefs,
},
},
},
],
});Usage
Direct Usage
Import test and expect directly from the package:
import { test, expect } from 'playwright-clipboard-testing';
test('should copy text to clipboard', async ({ page, clipboard }) => {
await page.goto('https://example.com');
await page.locator('#copy-button').click();
await expect(clipboard).toHaveTextContent('Hello, World!');
});Extended Usage
If you already have a custom test fixture file, extend Playwright's test and expect with clipboardFixtures and clipboardMatchers:
import { expect as baseExpect, test as baseTest } from '@playwright/test';
import { type ClipboardHandler, clipboardFixtures } from 'playwright-clipboard-testing/fixtures';
import { clipboardMatchers } from 'playwright-clipboard-testing/matchers';
export const test = baseTest.extend<{ clipboard: ClipboardHandler }>(clipboardFixtures);
export const expect = baseExpect.extend(clipboardMatchers);
Subpath Exports
The package provides dedicated subpath exports to import specific utilities when extending Playwright:
| Import Path | Description |
|:-----------------------------------------|:---------------------------------------------------------------------------------------------------------------------------|
| playwright-clipboard-testing | Pre-configured test runner and expect assertion function with built-in clipboard support. |
| playwright-clipboard-testing/fixtures | clipboardFixtures for extending custom test setups, along with the ClipboardHandler utility class and related types. |
| playwright-clipboard-testing/matchers | clipboardMatchers object and its ClipboardMatchers type definition for extending custom Playwright expect. |
| playwright-clipboard-testing/constants | firefoxClipboardPrefs for browser contexts and regular expression PATTERNS used by matchers. |
API
Fixtures
The package exports the following fixtures for Playwright test configuration:
clipboardFixtures— Object containing bothcontextandclipboardfixtures. Recommended for extending test fixtures.contextFixture(context) — Playwright context fixture that automatically grantsclipboard-readandclipboard-writepermissions in Chromium.clipboardFixture(clipboard) — Playwright test fixture that provides access to theClipboardHandlerinstance in your tests.
ClipboardHandler
The clipboard fixture provides direct access to the ClipboardHandler instance for managing clipboard state:
| Method | Return Type | Description |
|:---------------------|:------------------|:-------------------------------------------------------------------------------------------------------------------------|
| read() | Promise<string> | Reads plain text content from the clipboard. |
| write(text) | Promise<void> | Writes the specified plain text to the clipboard. |
| readJSON<T>() | Promise<T> | Reads clipboard content and parses it as a JSON object of type T. Throws an error if invalid JSON. |
| writeJSON<T>(data) | Promise<void> | Serializes an object of type T to JSON and writes it to the clipboard. Throws an error if object cannot be serialized. |
| clear() | Promise<void> | Clears all clipboard content. |
toBeBlank Matcher
expect(clipboard).toBeBlank(options?)
Asserts that the clipboard is empty. Uses Playwright's smart polling mechanism to wait for the clipboard to update.
options.timeout: number (optional, default: 10000ms)options.trim: boolean (optional, default: false)— Trims whitespace from the clipboard content before checking if it's blank.
// assert that the clipboard is empty
await expect(clipboard).toBeBlank();// assert that the clipboard is not empty with a custom timeout
await expect(clipboard).not.toBeBlank({ timeout: 5000 });toHaveContentLength Matcher
expect(clipboard).toHaveContentLength(expected, options?)
Asserts that the clipboard content has the expected length. Uses Playwright's smart polling mechanism to wait for the clipboard to update.
expected: number— Expected length of the clipboard content.options.timeout: number (optional, default: 10000ms)— Time in milliseconds to wait for the clipboard content to match.options.trim: boolean (optional, default: false)— Trims whitespace from the clipboard content before checking its length.
// assert that the clipboard content has the expected length
await expect(clipboard).toHaveContentLength(13);// assert that the clipboard content does not have the expected length with trim option
await expect(clipboard).not.toHaveContentLength(10, { trim: true });toHaveTextContent Matcher
expect(clipboard).toHaveTextContent(expected, options?)
Asserts that the clipboard content matches the expected string or regular expression. Uses Playwright's smart polling mechanism to wait for the clipboard to update.
expected: string | RegExp— Expected text string or regular expression to match against.options.timeout: number (optional, default: 10000ms)— Time in milliseconds to wait for the clipboard content to match.options.ignoreCase: boolean (optional, default: false)— Ignores case when comparing strings or matching regular expressions.options.trim: boolean (optional, default: false)— Trims whitespace from both expected and actual string before comparison.
// assert that the clipboard contains the expected text
await expect(clipboard).toHaveTextContent('Hello, World!');// assert that the clipboard text matches a regular expression
await expect(clipboard).toHaveTextContent(/Hello, World!/i);// assert that the clipboard does not contain the expected text with a custom timeout
await expect(clipboard).not.toHaveTextContent('Async copied value', { timeout: 5000 });toHaveJSONContent Matcher
expect(clipboard).toHaveJSONContent(expected, options?)
Asserts that the clipboard content matches the expected JSON value. Uses Playwright's smart polling mechanism to wait for the clipboard to update.
expected: unknown— Expected JSON value to compare against.options.timeout: number (optional, default: 10000ms)— Time in milliseconds to wait for the clipboard content to match.
// assert that the clipboard contains the expected JSON data
await expect(clipboard).toHaveJSONContent({ message: 'Hello, World!' });// assert that the clipboard does not contain the expected JSON data with a custom timeout
await expect(clipboard).not.toHaveJSONContent({ message: 'Async copied value' }, { timeout: 5000 });toMatchJSONContent Matcher
expect(clipboard).toMatchJSONContent(expected, options?)
Asserts that the expected JSON object is a subset of the clipboard content. Uses Playwright's smart polling mechanism to wait for the clipboard to update.
expected: unknown— Expected JSON subset object to compare against.options.timeout: number (optional, default: 10000ms)— Time in milliseconds to wait for the clipboard content to match.
// assert that the clipboard contains a subset of the expected JSON data
await expect(clipboard).toMatchJSONContent({ status: 'success' });// assert that the clipboard does not contain a subset of the expected JSON data with a custom timeout
await expect(clipboard).not.toMatchJSONContent({ status: 'failed' }, { timeout: 5000 });PATTERNS
The package exports pre-defined regular expression patterns for common data formats (PATTERNS), which can be passed directly to toHaveTextContent:
| Pattern | Description | Example Match |
|:------------|:-------------------------------------|:------------------------------------------|
| UUID | UUID v1–v5 format | 123e4567-e89b-12d3-a456-426614174000 |
| EMAIL | Email address format | [email protected] |
| PHONE | Phone number in E.164 format | +1234567890 |
| JWT | JWT token format | header.payload.signature |
| BEARER | Bearer authentication token format | Bearer token123 |
| HEX_COLOR | HEX color format | #FFF, #FFFFFF, #FFFFFFFF |
| IP.V4 | IPv4 address format | 192.168.1.1 |
| IP.V6 | IPv6 address format | 2001:0db8:85a3:0000:0000:8a2e:0370:7334 |
| IP.ANY | Any IP address format (IPv4 or IPv6) | 192.168.1.1 or 2001:db8::1 |
To use a pattern in your test, import PATTERNS and pass the desired pattern to toHaveTextContent:
import { expect, test } from 'playwright-clipboard-testing';
import { PATTERNS } from 'playwright-clipboard-testing/constants';
test('should copy UUID to clipboard', async ({ page, clipboard }) => {
await page.goto('https://example.com');
await page.locator('#copy-uuid-button').click();
await expect(clipboard).toHaveTextContent(PATTERNS.UUID);
});Author
Sergii Oleksenko [email protected]
License
If you find this project useful, give it a ⭐️ on GitHub!
