Skip to content

ever-co/ever-works / .agents/skills/playwright-best-practices

playwright-best-practices

Verified

Use when writing Playwright tests, fixing flaky tests, debugging failures, implementing Page Object Model, configuring CI/CD, optimizing performance, mocking APIs, handling authentication or OAuth, testing accessibility (axe-core), file uploads/downloads, date/time mocking, WebSockets, geolocation, permissions, multi-tab/popup flows, mobile/responsive layouts, touch gestures, GraphQL, error handling, offline mode, multi-user collaboration, third-party services (payments, email verification), console error monitoring, global setup/teardown, test annotations (skip, fixme, slow), test tags (@smoke, @fast, @critical, filtering with --grep), project dependencies, security testing (XSS, CSRF, auth), performance budgets (Web Vitals, Lighthouse), iframes, component testing, canvas/WebGL, service workers/PWA, test coverage, i18n/localization, Electron apps, or browser extension testing. Covers E2E, component, API, visual, accessibility, security, Electron, and extension testing.

FileKindSize
LICENSE.mdmarkdown1.0 KB
README.mdmarkdown9.9 KB
SKILL.mdskill md25.7 KB
advanced/authentication-flows.mdmarkdown10.4 KB
advanced/authentication.mdmarkdown29.4 KB
advanced/clock-mocking.mdmarkdown9.4 KB
advanced/mobile-testing.mdmarkdown10.3 KB
advanced/multi-context.mdmarkdown8.2 KB
advanced/multi-user.mdmarkdown10.9 KB
advanced/network-advanced.mdmarkdown10.1 KB
advanced/third-party.mdmarkdown11.1 KB
architecture/pom-vs-fixtures.mdmarkdown11.4 KB
architecture/test-architecture.mdmarkdown14.3 KB
architecture/when-to-mock.mdmarkdown11.9 KB
browser-apis/browser-apis.mdmarkdown10.1 KB
browser-apis/iframes.mdmarkdown11.1 KB
browser-apis/service-workers.mdmarkdown13.1 KB
browser-apis/websockets.mdmarkdown9.9 KB
core/annotations.mdmarkdown10.4 KB
core/assertions-waiting.mdmarkdown9.1 KB
core/configuration.mdmarkdown13.7 KB
core/fixtures-hooks.mdmarkdown11.2 KB
core/global-setup.mdmarkdown12.4 KB
core/locators.mdmarkdown6.4 KB
core/page-object-model.mdmarkdown7.7 KB
core/projects-dependencies.mdmarkdown8.1 KB
core/test-data.mdmarkdown11.3 KB
core/test-suite-structure.mdmarkdown9.1 KB
core/test-tags.mdmarkdown6.7 KB
debugging/console-errors.mdmarkdown9.3 KB
debugging/debugging.mdmarkdown14.7 KB
debugging/error-testing.mdmarkdown9.2 KB
debugging/flaky-tests.mdmarkdown14.5 KB
frameworks/angular.mdmarkdown18.9 KB
frameworks/nextjs.mdmarkdown13.4 KB
frameworks/react.mdmarkdown17.5 KB
frameworks/vue.mdmarkdown17.3 KB
infrastructure-ci-cd/ci-cd.mdmarkdown10.4 KB
infrastructure-ci-cd/docker.mdmarkdown7.0 KB
infrastructure-ci-cd/github-actions.mdmarkdown15.1 KB
infrastructure-ci-cd/gitlab.mdmarkdown10.9 KB
infrastructure-ci-cd/other-providers.mdmarkdown14.2 KB
infrastructure-ci-cd/parallel-sharding.mdmarkdown11.6 KB
infrastructure-ci-cd/performance.mdmarkdown11.3 KB
infrastructure-ci-cd/reporting.mdmarkdown11.4 KB
infrastructure-ci-cd/test-coverage.mdmarkdown12.0 KB
testing-patterns/accessibility.mdmarkdown8.7 KB
testing-patterns/api-testing.mdmarkdown23.5 KB
testing-patterns/browser-extensions.mdmarkdown13.0 KB
testing-patterns/canvas-webgl.mdmarkdown12.3 KB
testing-patterns/component-testing.mdmarkdown11.0 KB
testing-patterns/drag-drop.mdmarkdown17.4 KB
testing-patterns/electron.mdmarkdown12.8 KB
testing-patterns/file-operations.mdmarkdown10.0 KB
testing-patterns/file-upload-download.mdmarkdown16.5 KB
testing-patterns/forms-validation.mdmarkdown21.3 KB
testing-patterns/graphql-testing.mdmarkdown8.6 KB
testing-patterns/i18n.mdmarkdown12.3 KB
testing-patterns/performance-testing.mdmarkdown11.5 KB
testing-patterns/security-testing.mdmarkdown11.5 KB
testing-patterns/visual-regression.mdmarkdown18.4 KB

testing-patterns/file-upload-download.md

View on GitHub
# File Upload and Download Testing

> **When to use**: Testing file uploads (single, multiple, drag-and-drop), downloads (content verification, filename, type), upload progress indicators, or file type/size restrictions.

## Table of Contents

1. [Downloading Files](#downloading-files)
2. [Single File Upload](#single-file-upload)
3. [Multiple File Upload](#multiple-file-upload)
4. [Drag-and-Drop Zones](#drag-and-drop-zones)
5. [File Chooser Dialog](#file-chooser-dialog)
6. [Upload Progress and Cancellation](#upload-progress-and-cancellation)
7. [Retry After Failure](#retry-after-failure)
8. [File Type and Size Restrictions](#file-type-and-size-restrictions)
9. [Image Preview](#image-preview)
10. [Authenticated Downloads](#authenticated-downloads)
11. [Tips](#tips)

---

## Downloading Files

### Capturing Downloads and Verifying Content

```typescript
import { test, expect } from '@playwright/test';
import fs from 'fs';
import path from 'path';

test('verifies downloaded CSV content', async ({ page }) => {
	await page.goto('/exports');

	// Set up download listener BEFORE triggering the download
	const downloadPromise = page.waitForEvent('download');
	await page.getByRole('link', { name: 'transactions.csv' }).click();

	const download = await downloadPromise;
	const savePath = path.join(__dirname, '../tmp', download.suggestedFilename());
	await download.saveAs(savePath);

	const content = fs.readFileSync(savePath, 'utf-8');
	expect(content).toContain('id,amount,date');
	expect(content).toContain('1001,250.00,2025-01-15');

	const rows = content.trim().split('\n');
	expect(rows.length).toBeGreaterThan(1);

	fs.unlinkSync(savePath);
});

test('reads download via stream without disk I/O', async ({ page }) => {
	await page.goto('/exports');

	const downloadPromise = page.waitForEvent('download');
	await page.getByRole('link', { name: 'transactions.csv' }).click();

	const download = await downloadPromise;
	const readable = await download.createReadStream();
	const chunks: Buffer[] = [];

	for await (const chunk of readable!) {
		chunks.push(Buffer.from(chunk));
	}

	const content = Buffer.concat(chunks).toString('utf-8');
	expect(content).toContain('id,amount,date');
});
```

### Verifying Filename and Format

```typescript
test('export filename matches selected format', async ({ page }) => {
	await page.goto('/analytics');

	const downloadPromise = page.waitForEvent('download');
	await page.getByRole('button', { name: 'Export PDF' }).click();

	const download = await downloadPromise;
	expect(download.suggestedFilename()).toMatch(/^analytics-\d{4}-\d{2}-\d{2}\.pdf$/);
});

test('format selector changes output extension', async ({ page }) => {
	await page.goto('/analytics');

	await page.getByLabel('Format').selectOption('csv');
	const csvDownload = page.waitForEvent('download');
	await page.getByRole('button', { name: 'Download' }).click();
	expect((await csvDownload).suggestedFilename()).toMatch(/\.csv$/);

	await page.getByLabel('Format').selectOption('xlsx');
	const xlsxDownload = page.waitForEvent('download');
	await page.getByRole('button', { name: 'Download' }).click();
	expect((await xlsxDownload).suggestedFilename()).toMatch(/\.xlsx$/);
});
```

### Checking Response Headers

```typescript
test('download response has correct MIME type', async ({ page }) => {
	await page.goto('/analytics');

	const responsePromise = page.waitForResponse('**/api/analytics/export**');
	const downloadPromise = page.waitForEvent('download');

	await page.getByRole('button', { name: 'Export PDF' }).click();

	const response = await responsePromise;
	expect(response.headers()['content-type']).toContain('application/pdf');
	expect(response.headers()['content-disposition']).toContain('attachment');

	await downloadPromise;
});
```

### Handling Download Failures

```typescript
test('shows error when download fails', async ({ page }) => {
	await page.route('**/api/analytics/export**', async (route) => {
		await route.fulfill({
			status: 500,
			contentType: 'application/json',
			body: JSON.stringify({ error: 'Generation failed' })
		});
	});

	await page.goto('/analytics');
	await page.getByRole('button', { name: 'Export PDF' }).click();

	await expect(page.getByRole('alert')).toContainText(/failed|error/i);
});
```

---

## Single File Upload

### From Fixture File

```typescript
import path from 'path';

test('uploads document from fixture', async ({ page }) => {
	await page.goto('/attachments');

	const fileInput = page.locator('input[type="file"]');
	await fileInput.setInputFiles(path.resolve(__dirname, '../fixtures/invoice.pdf'));

	await expect(page.getByText('invoice.pdf')).toBeVisible();

	await page.getByRole('button', { name: 'Upload' }).click();
	await expect(page.getByRole('alert')).toContainText('uploaded successfully');
	await expect(page.getByRole('link', { name: 'invoice.pdf' })).toBeVisible();
});
```

### From In-Memory Buffer

```typescript
test('uploads in-memory CSV', async ({ page }) => {
	await page.goto('/attachments');

	const fileInput = page.locator('input[type="file"]');
	await fileInput.setInputFiles({
		name: 'contacts.csv',
		mimeType: 'text/csv',
		buffer: Buffer.from('name,email\nAlice,alice@acme.com\nBob,bob@acme.com')
	});

	await expect(page.getByText('contacts.csv')).toBeVisible();
	await page.getByRole('button', { name: 'Upload' }).click();
	await expect(page.getByRole('alert')).toContainText('uploaded successfully');
});
```

### Clearing Selection

```typescript
test('clears selected file', async ({ page }) => {
	await page.goto('/attachments');

	const fileInput = page.locator('input[type="file"]');
	await fileInput.setInputFiles({
		name: 'draft.txt',
		mimeType: 'text/plain',
		buffer: Buffer.from('draft content')
	});

	await expect(page.getByText('draft.txt')).toBeVisible();

	// Clear via API
	await fileInput.setInputFiles([]);
	await expect(page.getByText('draft.txt')).not.toBeVisible();
});
```

---

## Multiple File Upload

```typescript
test('uploads multiple files at once', async ({ page }) => {
	await page.goto('/attachments');

	const fileInput = page.locator('input[type="file"]');
	await fileInput.setInputFiles([
		{ name: 'doc1.pdf', mimeType: 'application/pdf', buffer: Buffer.from('pdf1') },
		{ name: 'doc2.pdf', mimeType: 'application/pdf', buffer: Buffer.from('pdf2') },
		{ name: 'doc3.pdf', mimeType: 'application/pdf', buffer: Buffer.from('pdf3') }
	]);

	await expect(page.getByText('doc1.pdf')).toBeVisible();
	await expect(page.getByText('doc2.pdf')).toBeVisible();
	await expect(page.getByText('doc3.pdf')).toBeVisible();
	await expect(page.getByText('3 files selected')).toBeVisible();

	await page.getByRole('button', { name: 'Upload all' }).click();
	await expect(page.getByRole('alert')).toContainText('3 files uploaded');
});

test('removes one file from selection', async ({ page }) => {
	await page.goto('/attachments');

	const fileInput = page.locator('input[type="file"]');
	await fileInput.setInputFiles([
		{ name: 'keep.txt', mimeType: 'text/plain', buffer: Buffer.from('keep') },
		{ name: 'discard.txt', mimeType: 'text/plain', buffer: Buffer.from('discard') }
	]);

	const discardRow = page.getByText('discard.txt').locator('..');
	await discardRow.getByRole('button', { name: /remove|delete|×/i }).click();

	await expect(page.getByText('discard.txt')).not.toBeVisible();
	await expect(page.getByText('keep.txt')).toBeVisible();
});
```

---

## Drag-and-Drop Zones

Drop zones always have an underlying `input[type="file"]`—target it directly instead of simulating OS-level drag events.

```typescript
test('uploads via drop zone', async ({ page }) => {
	await page.goto('/attachments');

	const dropZone = page.locator('[data-testid="drop-zone"]');
	await expect(dropZone).toContainText(/drag.*here|drop.*files/i);

	const fileInput = page.locator('input[type="file"]');
	await fileInput.setInputFiles({
		name: 'dropped.pdf',
		mimeType: 'application/pdf',
		buffer: Buffer.from('pdf-content')
	});

	await expect(dropZone.getByText('dropped.pdf')).toBeVisible();
	await page.getByRole('button', { name: 'Upload' }).click();
	await expect(page.getByRole('alert')).toContainText('uploaded successfully');
});

test('shows visual feedback on drag-over', async ({ page }) => {
	await page.goto('/attachments');

	const dropZone = page.locator('[data-testid="drop-zone"]');

	await dropZone.dispatchEvent('dragenter', {
		dataTransfer: { types: ['Files'], files: [] }
	});

	await expect(dropZone).toHaveClass(/active|highlight|drag-over/);
	await expect(dropZone).toContainText(/release|drop now/i);

	await dropZone.dispatchEvent('dragleave');
	await expect(dropZone).not.toHaveClass(/active|highlight|drag-over/);
});
```

---

## File Chooser Dialog

```typescript
test('uploads via native file chooser', async ({ page }) => {
	await page.goto('/attachments');

	const fileChooserPromise = page.waitForEvent('filechooser');
	await page.getByRole('button', { name: 'Choose file' }).click();

	const fileChooser = await fileChooserPromise;
	expect(fileChooser.isMultiple()).toBe(false);

	await fileChooser.setFiles({
		name: 'selected.pdf',
		mimeType: 'application/pdf',
		buffer: Buffer.from('pdf-content')
	});

	await expect(page.getByText('selected.pdf')).toBeVisible();
});
```

---

## Upload Progress and Cancellation

```typescript
test('displays upload progress for large file', async ({ page }) => {
	await page.goto('/attachments');

	const fileInput = page.locator('input[type="file"]');
	const largeBuffer = Buffer.alloc(5 * 1024 * 1024, 'x');

	await fileInput.setInputFiles({
		name: 'dataset.bin',
		mimeType: 'application/octet-stream',
		buffer: largeBuffer
	});

	await page.getByRole('button', { name: 'Upload' }).click();

	const progressBar = page.getByRole('progressbar');
	await expect(progressBar).toBeVisible();

	await expect(async () => {
		const value = await progressBar.getAttribute('aria-valuenow');
		expect(Number(value)).toBeGreaterThan(0);
	}).toPass({ timeout: 10000 });

	await expect(progressBar).not.toBeVisible({ timeout: 60000 });
	await expect(page.getByRole('alert')).toContainText('uploaded successfully');
});

test('cancels in-progress upload', async ({ page }) => {
	await page.route('**/api/attachments/upload', async (route) => {
		await new Promise((resolve) => setTimeout(resolve, 10000));
		await route.continue();
	});

	await page.goto('/attachments');

	const fileInput = page.locator('input[type="file"]');
	await fileInput.setInputFiles({
		name: 'large.bin',
		mimeType: 'application/octet-stream',
		buffer: Buffer.alloc(5 * 1024 * 1024, 'x')
	});

	await page.getByRole('button', { name: 'Upload' }).click();
	await expect(page.getByRole('progressbar')).toBeVisible();

	await page.getByRole('button', { name: 'Cancel upload' }).click();

	await expect(page.getByRole('progressbar')).not.toBeVisible();
	await expect(page.getByText(/cancelled|aborted/i)).toBeVisible();
	await expect(page.getByRole('link', { name: 'large.bin' })).not.toBeVisible();
});
```

---

## Retry After Failure

```typescript
test('retries failed upload', async ({ page }) => {
	let attempt = 0;

	await page.route('**/api/attachments/upload', async (route) => {
		attempt++;
		if (attempt === 1) {
			await route.fulfill({
				status: 500,
				contentType: 'application/json',
				body: JSON.stringify({ error: 'Server error' })
			});
		} else {
			await route.fulfill({
				status: 200,
				contentType: 'application/json',
				body: JSON.stringify({ id: 'abc', name: 'data.csv' })
			});
		}
	});

	await page.goto('/attachments');

	const fileInput = page.locator('input[type="file"]');
	await fileInput.setInputFiles({
		name: 'data.csv',
		mimeType: 'text/csv',
		buffer: Buffer.from('col1,col2\nval1,val2')
	});

	await page.getByRole('button', { name: 'Upload' }).click();
	await expect(page.getByText(/upload failed|error/i)).toBeVisible();

	await page.getByRole('button', { name: /retry/i }).click();
	await expect(page.getByRole('alert')).toContainText('uploaded successfully');
	expect(attempt).toBe(2);
});
```

---

## File Type and Size Restrictions

### Validating Allowed Types

```typescript
test('accepts allowed file types', async ({ page }) => {
	await page.goto('/attachments');

	const fileInput = page.locator('input[type="file"]');
	await expect(fileInput).toHaveAttribute('accept', /\.pdf|\.doc|\.docx|\.txt/);

	await fileInput.setInputFiles({
		name: 'report.pdf',
		mimeType: 'application/pdf',
		buffer: Buffer.from('pdf-content')
	});

	await expect(page.getByText('report.pdf')).toBeVisible();
	await expect(page.getByText(/not allowed|invalid/i)).not.toBeVisible();
});

test('rejects disallowed file types', async ({ page }) => {
	await page.goto('/attachments');

	const fileInput = page.locator('input[type="file"]');
	// setInputFiles bypasses the accept attribute—tests JavaScript validation
	await fileInput.setInputFiles({
		name: 'malware.exe',
		mimeType: 'application/x-msdownload',
		buffer: Buffer.from('exe-content')
	});

	await expect(page.getByRole('alert')).toContainText(/not allowed|unsupported file type|only .pdf, .doc/i);
	await expect(page.getByText('malware.exe')).not.toBeVisible();
});
```

### Enforcing Size Limits

```typescript
test('rejects oversized file', async ({ page }) => {
	await page.goto('/attachments');

	const fileInput = page.locator('input[type="file"]');
	const oversizedBuffer = Buffer.alloc(11 * 1024 * 1024, 'x');

	await fileInput.setInputFiles({
		name: 'huge.pdf',
		mimeType: 'application/pdf',
		buffer: oversizedBuffer
	});

	await expect(page.getByRole('alert')).toContainText(/file.*too large|exceeds.*10 ?MB/i);
	await expect(page.getByText('huge.pdf')).not.toBeVisible();
});
```

### Enforcing File Count Limits

```typescript
test('rejects too many files', async ({ page }) => {
	await page.goto('/attachments');

	const fileInput = page.locator('input[type="file"]');
	const files = Array.from({ length: 6 }, (_, i) => ({
		name: `file-${i + 1}.txt`,
		mimeType: 'text/plain' as const,
		buffer: Buffer.from(`content ${i + 1}`)
	}));

	await fileInput.setInputFiles(files);

	await expect(page.getByRole('alert')).toContainText(/maximum.*5 files|too many files/i);
});
```

### Validating Image Dimensions

```typescript
test('rejects image below minimum dimensions', async ({ page }) => {
	await page.goto('/profile/avatar');

	const fileInput = page.locator('input[type="file"]');
	// Minimal 1x1 PNG
	const tinyPng = Buffer.from(
		'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
		'base64'
	);

	await fileInput.setInputFiles({
		name: 'tiny.png',
		mimeType: 'image/png',
		buffer: tinyPng
	});

	await expect(page.getByRole('alert')).toContainText(/minimum.*dimensions|too small/i);
});
```

---

## Image Preview

```typescript
test('shows image preview after selection', async ({ page }) => {
	await page.goto('/profile/avatar');

	const fileInput = page.locator('input[type="file"]');
	await fileInput.setInputFiles(path.resolve(__dirname, '../fixtures/photo.jpg'));

	const preview = page.getByRole('img', { name: /preview|avatar/i });
	await expect(preview).toBeVisible();

	const src = await preview.getAttribute('src');
	expect(src).toMatch(/^(blob:|data:image)/);
});
```

---

## Authenticated Downloads

```typescript
test('downloads file requiring authentication', async ({ page, request }) => {
	await page.goto('/attachments');

	// Browser download works because cookies are sent
	const downloadPromise = page.waitForEvent('download');
	await page.getByRole('link', { name: 'confidential.pdf' }).click();

	const download = await downloadPromise;
	expect(download.suggestedFilename()).toBe('confidential.pdf');

	// Verify via API request (carries auth context)
	const response = await request.get('/api/attachments/456/download');
	expect(response.ok()).toBeTruthy();
	expect(response.headers()['content-type']).toContain('application/pdf');
});
```

---

## Tips

1. **Use `setInputFiles` for uploads**. Even drag-and-drop zones have an underlying `input[type="file"]`. Target it directly instead of simulating OS-level drag events.

2. **Prefer in-memory buffers**. Creating files with `Buffer.from()` keeps tests self-contained. Use fixture files only when you need real content (e.g., a valid PDF your app parses).

3. **Set up download listener before clicking**. Call `page.waitForEvent('download')` before the click that triggers the download—otherwise you may miss the event.

4. **Use `createReadStream()` for content verification**. Reading directly from the stream avoids disk I/O and cleanup of temporary files.

5. **Test both `accept` attribute and JavaScript validation**. The HTML `accept` attribute only filters the OS file dialog. `setInputFiles()` bypasses it, which is exactly what you need to test your app's JavaScript validation.
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall