Cypress 18 ๐ฒ File Uploads โ cy.selectFile and drag-and-drop simulation
File uploads sit at an awkward intersection of browser APIs and operating system behavior. A traditional <input type="file"> opens a native dialog that no automation tool can control, and drag-and-drop zones respond to low-level drag events that a simple .click() cannot reproduce. Cypress solves both with a single command: cy.selectFile(). It assigns files to an input programmatically in its default select mode, and simulates the complete drag-and-drop event sequence in drag-drop mode, allowing tests to exercise every upload path without touching the OS dialog.
This chapter covers cy.selectFile() in depth: how the two action modes differ, how to supply files as disk paths, aliases, buffers, or inline objects, how to simulate dropping files onto a page or a specific element, and how to construct dynamic file content when no fixture exists. It also covers multi-file uploads, MIME type control, and the migration from the deprecated cypress-file-upload plugin. By the end, you will be able to test any file ingestion flowโinput-based or drag-basedโwithout committing large binaries or wrestling with native dialogs.
Key point: cy.selectFile() has two modes controlled by the action option. The default 'select' mode sets files on an <input type="file"> element, bypassing the native dialog entirely. The 'drag-drop' mode simulates the full sequence of drag events over any DOM element, enabling tests of dropzones that have no underlying input element.
Why cy.selectFile exists
The native dialog problem. An <input type="file"> opens the operating system’s file picker when clicked. This dialog is not part of the DOM, not styled by CSS, and not reachable by any browser automation API. Older Cypress approaches required the cypress-file-upload plugin, which injected files by manipulating the input’s files propertyโa workaround that worked but lived outside the core API and had its own compatibility constraints. cy.selectFile() brings this capability into Cypress itself, with first-class support for actionability checks, timeouts, and the Command Log .
The drag-and-drop reality gap. Many modern upload interfacesโemail attachments, cloud storage, image editorsโpresent a dropzone rather than a visible input. The user drags a file from their desktop and drops it onto the page. Reproducing this in a test requires dispatching dragenter, dragover, and drop events with a properly constructed DataTransfer object. cy.selectFile() with action: 'drag-drop' performs this entire sequence, dispatching the events over the target element or the document, so the application’s drop handlers fire exactly as they would for a real user .
The fixture flexibility problem. A test that uploads a 50 MB video should not commit a 50 MB video to the repository. A test that verifies a file-size validation should not need a real file at all. cy.selectFile() accepts file content as a path string, a Cypress.Buffer, an alias to a previously loaded fixture, or an inline object with contents, fileName, and mimeType. The inline buffer approach lets tests generate content dynamicallyโa file of exactly 6 MB, a JSON payload that changes per run, or ten files in a loopโwithout any disk artifacts .
a. Selecting files with the default select mode
In select mode, the subject of cy.selectFile() must be a single <input type="file"> element or a <label> associated with one. The command assigns the supplied file(s) to the input and fires the change event, which is what the application listens for. The input does not need to be visibleโCypress locates it and sets its files programmatically .
// cypress/e2e/upload.cy.ts
describe('Document upload', () => {
it('uploads a file from a disk path', () => {
cy.visit('/documents');
// Path is resolved relative to the project root
cy.get('input[type="file"]')
.selectFile('cypress/fixtures/contract.pdf'); // โ
input receives the file
// Assert the application acknowledged the upload
cy.get('[data-test="file-name"]').should('contain', 'contract.pdf');
});
it('uploads multiple files', () => {
cy.visit('/documents');
// Pass an array for multi-file inputs
cy.get('input[type="file"]').selectFile([
'cypress/fixtures/photo.jpg',
'cypress/fixtures/notes.txt',
]);
cy.get('[data-test="file-count"]').should('have.text', '2 files selected');
});
});
The path is relative to the project rootโthe directory containing cypress.config.ts, not the spec file’s directory. If the file does not exist at that path, the command fails with a clear error. The select mode also accepts an object with a contents property for in-memory files, which is covered in section c .
The command yields the same subject it was given, but Cypress warns against chaining further commands that rely on that subject. After selectFile(), the input’s files property has been modified, and any chained assertion that depends on the input’s state may be unreliable. Assert against the application’s rendered output instead .
b. Simulating drag-and-drop with action drag-drop
Setting action: 'drag-drop' changes the command’s behavior entirely. The subject is no longer restricted to an input element; it can be any DOM element that represents a dropzone, or the document itself for full-page drops. Cypress dispatches the complete drag event sequenceโdragenter, dragover, and dropโwith a synthetic DataTransfer object containing the specified files .
describe('Drag-and-drop upload', () => {
it('drops a file onto a specific dropzone', () => {
cy.visit('/upload');
// The dropzone is a div, not an input
cy.get('[data-test="dropzone"]').selectFile(
'cypress/fixtures/report.csv',
{ action: 'drag-drop' } // โ
fires dragenter, dragover, drop
);
cy.get('[data-test="upload-status"]').should('contain', 'report.csv uploaded');
});
it('drops a file onto the page itself', () => {
cy.visit('/upload');
// Dropping over the document triggers page-level drop handlers
cy.document().selectFile(
'cypress/fixtures/image.png',
{ action: 'drag-drop' } // โ
subject is the document
);
cy.get('[data-test="preview"]').should('be.visible');
});
});
The drag-drop mode bypasses the native file dialog entirely, just like select mode. The difference is the event sequence and the acceptable subject. This means a dropzone implemented entirely in JavaScriptโlistening for drop on a <div> with no <input> anywhere in the DOMโcan be tested without adding test-only markup. The command respects actionability checks by default: the dropzone must be visible, stable, and able to receive pointer events. If the dropzone is covered by an overlay, the command fails unless { force: true } is passed .
c. Constructing dynamic files with buffers and inline objects
When a test needs content that does not exist on disk, cy.selectFile() accepts a Cypress.Buffer or an object with contents, fileName, and mimeType. The buffer approach is the most flexible: it creates a file entirely in memory, with content that can be computed per test run, sized precisely to test validation, or generated in a loop for multi-file scenarios .
describe('Dynamic file content', () => {
it('uploads a buffer with a custom name and MIME type', () => {
cy.visit('/import');
// Construct the file in memory; no disk artifact
cy.get('input[type="file"]').selectFile({
contents: Cypress.Buffer.from('name,email\nAlice,alice@example.com'),
fileName: 'users.csv', // name the app will see
mimeType: 'text/csv', // type for validation
});
cy.get('[data-test="row-count"]').should('have.text', '1 row imported');
});
it('generates multiple files in a loop', () => {
cy.visit('/bulk-upload');
const files = [];
for (let i = 1; i <= 5; i++) {
files.push(
Cypress.Buffer.from(`Content of file #${i}`) // โ
unique content per file
);
}
cy.get('input[type="file"]').selectFile(files);
cy.get('[data-test="file-count"]').should('have.text', '5 files');
});
it('tests a file size limit with a precisely sized buffer', () => {
cy.visit('/upload');
// 6 MB buffer to exceed a 5 MB limit
const oversized = Cypress.Buffer.alloc(6 * 1024 * 1024);
cy.get('input[type="file"]').selectFile({
contents: oversized,
fileName: 'huge.dat',
mimeType: 'application/octet-stream',
});
cy.get('[data-test="error"]').should('contain', 'File exceeds 5 MB');
});
});
The mimeType property matters for applications that validate file type before reading contents. If omitted, Cypress infers the MIME type from the fileName extension; if the extension is unknown, it defaults to an empty string . For a file named data.csv, inference yields text/csv; for report.xyz, it yields nothing, and the application’s type check may reject it. Supply mimeType explicitly when the test depends on a specific type being recognized.
The lastModified property defaults to Date.now() and is rarely set manually. It exists for tests that verify timestamp display or sorting by modification date.
Complete Example Session
// ============================================
// PART 1: IMPORT AND TEST SETUP
// ============================================
// cypress/e2e/file-workflow.cy.ts
describe('File upload workflow', () => {
// ============================================
// PART 2: STANDARD INPUT UPLOAD
// ============================================
it('uploads a fixture file to a file input', () => {
cy.visit('/documents');
cy.get('input[type="file"]')
.selectFile('cypress/fixtures/contract.pdf');
cy.get('[data-test="file-name"]').should('contain', 'contract.pdf');
});
// ============================================
// PART 3: MULTI-FILE SELECTION
// ============================================
it('selects multiple files at once', () => {
cy.visit('/documents');
cy.get('input[type="file"]').selectFile([
'cypress/fixtures/photo.jpg',
'cypress/fixtures/notes.txt',
]);
cy.get('[data-test="file-list"]').children().should('have.length', 2);
});
// ============================================
// PART 4: DRAG-AND-DROP ONTO A DROPZONE
// ============================================
it('drops a file onto a custom dropzone', () => {
cy.visit('/upload');
cy.get('[data-test="dropzone"]').selectFile(
'cypress/fixtures/report.csv',
{ action: 'drag-drop' }
);
cy.get('[data-test="dropzone"]').should('contain', 'report.csv');
});
// ============================================
// PART 5: PAGE-LEVEL DROP
// ============================================
it('drops a file onto the document body', () => {
cy.visit('/upload');
cy.document().selectFile(
'cypress/fixtures/image.png',
{ action: 'drag-drop' }
);
cy.get('[data-test="preview-img"]').should('be.visible');
});
// ============================================
// PART 6: IN-MEMORY BUFFER UPLOAD
// ============================================
it('uploads dynamically generated CSV content', () => {
cy.visit('/import');
cy.get('input[type="file"]').selectFile({
contents: Cypress.Buffer.from('id,name\n1,Alice\n2,Bob'),
fileName: 'users.csv',
mimeType: 'text/csv',
});
cy.get('[data-test="imported-count"]').should('have.text', '2');
});
// ============================================
// PART 7: MIME TYPE VALIDATION
// ============================================
it('rejects a file with the wrong MIME type', () => {
cy.visit('/upload');
cy.get('input[type="file"]').selectFile({
contents: Cypress.Buffer.from('fake executable'),
fileName: 'malware.exe',
mimeType: 'application/x-msdownload',
});
cy.get('[data-test="error"]').should('contain', 'File type not allowed');
});
// ============================================
// PART 8: FILE SIZE VALIDATION
// ============================================
it('rejects a file exceeding the size limit', () => {
cy.visit('/upload');
// 10 MB buffer for a 5 MB limit
const large = Cypress.Buffer.alloc(10 * 1024 * 1024);
cy.get('input[type="file"]').selectFile({
contents: large,
fileName: 'huge.zip',
mimeType: 'application/zip',
});
cy.get('[data-test="error"]').should('contain', 'File too large');
});
// ============================================
// PART 9: ALIASED FIXTURE UPLOAD
// ============================================
it('uploads a fixture loaded via cy.fixture and aliased', () => {
cy.fixture('config.json').as('configFile'); // load once
cy.visit('/upload');
cy.get('input[type="file"]').selectFile('@configFile'); // โ
alias reference
cy.get('[data-test="file-name"]').should('contain', 'config.json');
});
// ============================================
// PART 10: LOOPING DYNAMIC FILES FOR BULK UPLOAD
// ============================================
it('uploads five generated files in one action', () => {
cy.visit('/bulk');
const files = Array.from({ length: 5 }, (_, i) =>
Cypress.Buffer.from(`File number ${i + 1}`)
);
cy.get('input[type="file"]').selectFile(files);
cy.get('[data-test="bulk-count"]').should('have.text', '5');
});
});
The ten parts above cover the full range of cy.selectFile() usage: standard input upload, multi-file selection, dropzone drag-and-drop, document-level drop, in-memory buffer creation, MIME type validation, size limit testing, aliased fixture reuse, and loop-generated bulk files. Each test exercises a different ingestion path while relying on the same command.
Quick Reference
cy.selectFile Arguments
| Argument | Type | Purpose |
|---|---|---|
file | String, Array, Object, Buffer | Single file or array of files |
options.action | 'select' or 'drag-drop' | Mode of file assignment |
options.force | Boolean | Skip actionability checks |
options.log | Boolean | Show in Command Log (default true) |
File Input Types
| Type | Example | Source |
|---|---|---|
| Path string | 'cypress/fixtures/file.json' | Relative to project root |
| Alias | '@fixtureAlias' | From cy.fixture().as() |
| Buffer | Cypress.Buffer.from('text') | In-memory content |
| Object | { contents, fileName, mimeType } | Full control over metadata |
Action Modes
| Mode | Subject | Events Fired |
|---|---|---|
'select' (default) | <input type="file"> or associated <label> | change |
'drag-drop' | Any DOM element or cy.document() | dragenter, dragover, drop |
Object Properties
| Property | Required | Purpose |
|---|---|---|
contents | Yes | File body (Buffer, string, or object) |
fileName | No | Name the app sees; defaults to path filename or empty |
mimeType | No | Type for validation; inferred from extension |
lastModified | No | Timestamp; defaults to Date.now() |
Best Practices
โ Do This:
// Use the default select mode for standard file inputs
cy.get('input[type="file"]').selectFile('cypress/fixtures/doc.pdf'); // โ
// Use drag-drop for dropzones without an input element
cy.get('[data-test="dropzone"]').selectFile('file.csv', { action: 'drag-drop' }); // โ
// Generate content in memory to avoid binary fixtures
cy.get('input').selectFile({
contents: Cypress.Buffer.from('id,name\n1,Alice'), // โ
fileName: 'users.csv',
mimeType: 'text/csv',
});
// Supply mimeType explicitly when validation depends on it
cy.get('input').selectFile({ contents: buf, fileName: 'data', mimeType: 'text/csv' }); // โ
// Use Buffer.alloc for precise size-limit testing
const large = Cypress.Buffer.alloc(6 * 1024 * 1024); // โ
exactly 6 MB
โ Don’t Do This:
// Don't chain selectFile off cy directly
cy.selectFile('file.json'); // โ must be chained off a subject
// Don't pass raw text expecting it to be treated as contents
cy.get('input').selectFile('file contents'); // โ treated as a path, not content
// Don't use select mode on a non-input dropzone
cy.get('div.dropzone').selectFile('file.csv'); // โ throws: subject is not an input
// Don't rely on a chained subject after selectFile
cy.get('input').selectFile('file').should('have.value', 'file'); // โ unreliable
// Don't commit large binary fixtures when a buffer suffices
// cypress/fixtures/50mb-video.mp4 // โ use Buffer.alloc if content is synthetic
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
selectFile throws on a div | Used default select mode on non-input | Add { action: 'drag-drop' } |
| File not found error | Path not relative to project root | Use cypress/fixtures/... prefix |
| MIME type rejected | mimeType omitted and extension unknown | Supply mimeType explicitly |
| Drop event not firing | Target element covered by overlay | Add { force: true } or fix z-index |
| Alias not resolving | Fixture not loaded before use | Call cy.fixture().as() first |
| Chained assertion fails | Subject unreliable after selectFile | Assert on rendered app output instead |
Real-World Examples
1. Uploading a PDF from fixtures
cy.get('input[type="file"]').selectFile('cypress/fixtures/contract.pdf');
2. Dropping a CSV onto a dropzone
cy.get('[data-test="dropzone"]').selectFile('data.csv', { action: 'drag-drop' });
3. Uploading a dynamically named file
cy.get('input').selectFile({
contents: Cypress.Buffer.from('content'),
fileName: `report-${Date.now()}.txt`,
});
4. Testing file type rejection
cy.get('input').selectFile({
contents: Cypress.Buffer.from('fake'),
fileName: 'script.exe',
mimeType: 'application/x-msdownload',
});
5. Testing file size rejection
cy.get('input').selectFile({
contents: Cypress.Buffer.alloc(6 * 1024 * 1024),
fileName: 'large.dat',
});
6. Uploading multiple files as an array
cy.get('input').selectFile(['a.txt', 'b.txt', 'c.txt']);
7. Using an aliased fixture
cy.fixture('data.json').as('data');
cy.get('input').selectFile('@data');
8. Dropping onto the document body
cy.document().selectFile('image.png', { action: 'drag-drop' });
9. Generating multiple buffers in a loop
const files = Array.from({ length: 3 }, (_, i) =>
Cypress.Buffer.from(`File ${i + 1}`)
);
cy.get('input').selectFile(files);
10. Clearing a file selection
cy.get('input').selectFile([]); // empty array clears
Visual
Two Modes, One Command
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ cy.selectFile('file.csv', { action: ? }) โ
โ โ
โ action: 'select' (default) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Subject must be: <input type="file"> โ โ
โ โ or <label> connected to an input โ โ
โ โ โ โ
โ โ Behavior: โ โ
โ โ โข Sets input.files property โ โ
โ โ โข Fires 'change' event โ โ
โ โ โข Native dialog never opens โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ action: 'drag-drop' โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Subject can be: any DOM element โ โ
โ โ or cy.document() โ โ
โ โ โ โ
โ โ Behavior: โ โ
โ โ โข Creates DataTransfer with files โ โ
โ โ โข Fires 'dragenter' โ โ
โ โ โข Fires 'dragover' โ โ
โ โ โข Fires 'drop' โ โ
โ โ โข App's drop handler receives files โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
File Source Options
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ WHAT CAN BE PASSED TO selectFile() โ
โ โ
โ 1. Path string โ
โ 'cypress/fixtures/file.json' โ
โ โโโ read from disk, relative to project root โ
โ โ
โ 2. Alias โ
โ '@myFixture' โ
โ โโโ from cy.fixture().as('myFixture') โ
โ โ
โ 3. Cypress.Buffer โ
โ Cypress.Buffer.from('content') โ
โ โโโ in-memory, no disk artifact โ
โ โ
โ 4. Object with metadata โ
โ { contents, fileName, mimeType, lastModified } โ
โ โโโ full control, contents required โ
โ โ
โ 5. Array of any of the above โ
โ [path1, buffer2, {object3}] โ
โ โโโ multi-file upload โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Migration from cypress-file-upload
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ BEFORE (plugin) AFTER (cy.selectFile) โ
โ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ .attachFile( .selectFile( โ
โ 'fixture.json' 'cypress/fixtures/ โ
โ ) fixture.json' โ
โ ) โ
โ โ
โ .attachFile({ .selectFile({ โ
โ filePath: 'f.json', contents: 'f.json', โ
โ fileName: 'custom', fileName: 'custom', โ
โ mimeType: 'text/plain' mimeType: 'text/plain' โ
โ }) }) โ
โ โ
โ .attachFile( .selectFile( โ
โ 'fixture.json', 'cypress/fixtures/ โ
โ { subjectType: fixture.json', โ
โ 'drag-drop' } { action: 'drag-drop' } โ
โ ) ) โ
โ โ
โ Plugin removed. Command is built into Cypress. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Command | cy.selectFile(file, options?) |
| Default mode | 'select' โ sets files on an input |
| Drag mode | 'drag-drop' โ fires drag event sequence |
| Disk path | Relative to project root |
| Alias | '@fixtureName' from cy.fixture().as() |
| In-memory content | Cypress.Buffer.from(...) or { contents } |
| MIME type | Optional; inferred from extension |
| Multi-file | Pass an array |
| Clear selection | selectFile([]) |
| Migration source | Replaces cypress-file-upload plugin |
Key takeaways:
- Two modes solve two problems.
'select'mode handles standard file inputs by setting thefilesproperty and firingchange.'drag-drop'mode handles dropzones by dispatching the full drag event sequence. The subject element determines which mode is appropriate. - The native dialog is never opened. Both modes bypass the OS file picker entirely.
selectFile()is not a replacement for clicking an input; it is a replacement for the user’s file selection step. - Paths are relative to the project root.
'cypress/fixtures/file.json'works;'./fixtures/file.json'from inside a spec file does not. The path is resolved against the directory containingcypress.config.ts. - Buffers eliminate binary fixtures.
Cypress.Buffer.from()creates content in memory,Cypress.Buffer.alloc()creates a buffer of a precise size. Tests that verify file size or type validation should use buffers, not committed files. - MIME type matters for validation. If the application checks
file.type, supplymimeTypeexplicitly. Inference from extension works for common types but fails for unknown extensions, defaulting to an empty string. - Assert on the application, not the input.
selectFile()yields the input element, but chaining assertions that depend on its state is unreliable. Assert on the rendered file name, the upload status, or the error message instead. - The cypress-file-upload plugin is obsolete.
cy.selectFile()is the built-in replacement. The migration is straightforward:attachFilebecomesselectFile,filePathbecomescontents, andsubjectType: 'drag-drop'becomesaction: 'drag-drop'.
Remember: File uploads in Cypress are not about opening dialogsโthey are about injecting files into the application’s ingestion path. cy.selectFile() does this in two ways: for an input, it sets the files and fires the event the app listens for; for a dropzone, it simulates the drag sequence the app’s handlers expect. The file itself can come from disk, from an alias, or from a buffer created in the test. The application never knows the difference. Test the input path with 'select', test the dropzone path with 'drag-drop', and generate content with buffers when the file’s existence on disk is incidental to what the test verifies.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!