Testing Guide
How to test components that use Dropup.
Setup
Install testing dependencies:
npm install -D vitest @testing-library/react @testing-library/user-event jsdom
Configure Vitest:
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: './src/test/setup.ts',
},
});
// src/test/setup.ts
import '@testing-library/jest-dom';
Basic Component Test
// components/Uploader.tsx
import { useDropup } from '@samithahansaka/dropup';
export function Uploader() {
const { files, getDropProps, getInputProps } = useDropup({
accept: 'image/*',
});
return (
<div {...getDropProps()} data-testid="dropzone">
<input {...getInputProps()} data-testid="file-input" />
<p>Drop images here</p>
<ul data-testid="file-list">
{files.map(file => (
<li key={file.id} data-testid="file-item">
{file.name}
</li>
))}
</ul>
</div>
);
}
// components/Uploader.test.tsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect } from 'vitest';
import { Uploader } from './Uploader';
describe('Uploader', () => {
it('renders dropzone', () => {
render(<Uploader />);
expect(screen.getByTestId('dropzone')).toBeInTheDocument();
expect(screen.getByText('Drop images here')).toBeInTheDocument();
});
it('accepts file input', async () => {
const user = userEvent.setup();
render(<Uploader />);
const input = screen.getByTestId('file-input');
const file = new File(['test'], 'test.png', { type: 'image/png' });
await user.upload(input, file);
expect(screen.getByTestId('file-item')).toHaveTextContent('test.png');
});
it('accepts multiple files', async () => {
const user = userEvent.setup();
render(<Uploader />);
const input = screen.getByTestId('file-input');
const files = [
new File(['test1'], 'photo1.png', { type: 'image/png' }),
new File(['test2'], 'photo2.png', { type: 'image/png' }),
];
await user.upload(input, files);
const items = screen.getAllByTestId('file-item');
expect(items).toHaveLength(2);
});
});
Testing Drag and Drop
import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect } from 'vitest';
import { Uploader } from './Uploader';
describe('Drag and Drop', () => {
it('shows drag state when dragging over', () => {
render(<Uploader />);
const dropzone = screen.getByTestId('dropzone');
fireEvent.dragEnter(dropzone, {
dataTransfer: {
types: ['Files'],
items: [{ kind: 'file' }],
},
});
expect(dropzone).toHaveAttribute('data-dragging', 'true');
});
it('handles file drop', () => {
render(<Uploader />);
const dropzone = screen.getByTestId('dropzone');
const file = new File(['test'], 'dropped.png', { type: 'image/png' });
fireEvent.drop(dropzone, {
dataTransfer: {
files: [file],
types: ['Files'],
},
});
expect(screen.getByText('dropped.png')).toBeInTheDocument();
});
});
Testing Validation
// components/ValidatedUploader.tsx
import { useDropup } from '@samithahansaka/dropup';
import { useState } from 'react';
export function ValidatedUploader() {
const [errors, setErrors] = useState<string[]>([]);
const { files, getDropProps, getInputProps } = useDropup({
accept: 'image/*',
maxSize: 1024 * 1024, // 1MB
onValidationError: (validationErrors) => {
const messages = validationErrors.flatMap(e => e.errors);
setErrors(messages);
},
});
return (
<div {...getDropProps()} data-testid="dropzone">
<input {...getInputProps()} data-testid="file-input" />
{errors.length > 0 && (
<ul data-testid="error-list">
{errors.map((error, i) => (
<li key={i} data-testid="error-item">{error}</li>
))}
</ul>
)}
</div>
);
}
// components/ValidatedUploader.test.tsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect } from 'vitest';
import { ValidatedUploader } from './ValidatedUploader';
describe('Validation', () => {
it('rejects wrong file type', async () => {
const user = userEvent.setup();
render(<ValidatedUploader />);
const input = screen.getByTestId('file-input');
const file = new File(['test'], 'document.pdf', { type: 'application/pdf' });
await user.upload(input, file);
expect(screen.getByTestId('error-list')).toBeInTheDocument();
});
it('rejects files over size limit', async () => {
const user = userEvent.setup();
render(<ValidatedUploader />);
const input = screen.getByTestId('file-input');
// Create a 2MB file (over 1MB limit)
const content = new Array(2 * 1024 * 1024).fill('a').join('');
const file = new File([content], 'large.png', { type: 'image/png' });
await user.upload(input, file);
expect(screen.getByTestId('error-list')).toBeInTheDocument();
});
});
Testing Upload
// components/UploadingComponent.tsx
import { useDropup } from '@samithahansaka/dropup';
export function UploadingComponent() {
const { files, actions, state, getDropProps, getInputProps } = useDropup({
upload: { url: '/api/upload' },
});
return (
<div {...getDropProps()} data-testid="dropzone">
<input {...getInputProps()} data-testid="file-input" />
{files.map(file => (
<div key={file.id} data-testid="file-status">
{file.status === 'uploading' && `Uploading: ${file.progress}%`}
{file.status === 'complete' && 'Done!'}
{file.status === 'error' && `Error: ${file.error?.message}`}
</div>
))}
<button
onClick={() => actions.upload()}
disabled={state.isUploading}
data-testid="upload-btn"
>
Upload
</button>
</div>
);
}
// components/UploadingComponent.test.tsx
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { UploadingComponent } from './UploadingComponent';
// Mock fetch
const mockFetch = vi.fn();
global.fetch = mockFetch;
describe('Upload', () => {
beforeEach(() => {
mockFetch.mockReset();
});
it('uploads files successfully', async () => {
mockFetch.mockResolvedValue({
ok: true,
json: () => Promise.resolve({ url: 'https://example.com/file.png' }),
});
const user = userEvent.setup();
render(<UploadingComponent />);
// Add file
const input = screen.getByTestId('file-input');
const file = new File(['test'], 'test.png', { type: 'image/png' });
await user.upload(input, file);
// Click upload
await user.click(screen.getByTestId('upload-btn'));
// Wait for completion
await waitFor(() => {
expect(screen.getByTestId('file-status')).toHaveTextContent('Done!');
});
expect(mockFetch).toHaveBeenCalledWith('/api/upload', expect.anything());
});
it('handles upload error', async () => {
mockFetch.mockRejectedValue(new Error('Network error'));
const user = userEvent.setup();
render(<UploadingComponent />);
const input = screen.getByTestId('file-input');
await user.upload(input, new File(['test'], 'test.png', { type: 'image/png' }));
await user.click(screen.getByTestId('upload-btn'));
await waitFor(() => {
expect(screen.getByTestId('file-status')).toHaveTextContent('Error');
});
});
});
Mocking useDropup
For isolated unit tests:
// __mocks__/@samithahansaka/dropup.ts
import { vi } from 'vitest';
export const useDropup = vi.fn(() => ({
files: [],
state: {
isDragging: false,
isDragAccept: false,
isDragReject: false,
isUploading: false,
progress: 0,
status: 'idle',
},
actions: {
upload: vi.fn(),
cancel: vi.fn(),
remove: vi.fn(),
reset: vi.fn(),
retry: vi.fn(),
addFiles: vi.fn(),
updateFileMeta: vi.fn(),
},
getDropProps: vi.fn(() => ({})),
getInputProps: vi.fn(() => ({ type: 'file' })),
openFileDialog: vi.fn(),
}));
// Usage in tests
import { vi } from 'vitest';
import { useDropup } from '@samithahansaka/dropup';
vi.mock('@samithahansaka/dropup');
const mockUseDropup = vi.mocked(useDropup);
describe('With mocked hook', () => {
it('renders with files', () => {
mockUseDropup.mockReturnValue({
files: [
{ id: '1', name: 'test.png', status: 'idle', progress: 0, size: 1000, type: 'image/png' },
],
// ... other values
});
render(<Uploader />);
expect(screen.getByText('test.png')).toBeInTheDocument();
});
});
Testing with MSW
Use Mock Service Worker for realistic API testing:
// src/test/handlers.ts
import { http, HttpResponse } from 'msw';
export const handlers = [
http.post('/api/upload', async ({ request }) => {
const formData = await request.formData();
const file = formData.get('file') as File;
return HttpResponse.json({
url: `https://example.com/uploads/${file.name}`,
});
}),
http.post('/api/upload-error', () => {
return HttpResponse.json(
{ error: 'Upload failed' },
{ status: 500 }
);
}),
];
// src/test/setup.ts
import { setupServer } from 'msw/node';
import { handlers } from './handlers';
export const server = setupServer(...handlers);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
E2E Testing with Playwright
// e2e/upload.spec.ts
import { test, expect } from '@playwright/test';
test.describe('File Upload', () => {
test('uploads a file', async ({ page }) => {
await page.goto('/upload');
// Get the file input
const fileInput = page.locator('input[type="file"]');
// Upload file
await fileInput.setInputFiles({
name: 'test.png',
mimeType: 'image/png',
buffer: Buffer.from('fake image content'),
});
// Verify file appears in list
await expect(page.locator('text=test.png')).toBeVisible();
// Click upload button
await page.click('button:has-text("Upload")');
// Wait for success
await expect(page.locator('text=Done')).toBeVisible();
});
test('drag and drop upload', async ({ page }) => {
await page.goto('/upload');
const dropzone = page.locator('[data-testid="dropzone"]');
// Create file data
const buffer = Buffer.from('test content');
// Simulate drag and drop
const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
await page.dispatchEvent('[data-testid="dropzone"]', 'drop', {
dataTransfer,
});
// Verify file added
await expect(page.locator('[data-testid="file-item"]')).toBeVisible();
});
});
Best Practices
- Test behavior, not implementation - Focus on what users see and do
- Use data-testid for reliability - Avoid testing by CSS classes
- Mock network requests - Use MSW or vi.mock for API calls
- Test edge cases - Empty states, errors, large files
- Test accessibility - Keyboard navigation, screen readers