| | |

Cypress 18 ๐ŸŒฒ File Uploads โ€” cy.selectFile and drag-and-drop simulation

โฑ๏ธ Estimated read: 15 min | |

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

ArgumentTypePurpose
fileString, Array, Object, BufferSingle file or array of files
options.action'select' or 'drag-drop'Mode of file assignment
options.forceBooleanSkip actionability checks
options.logBooleanShow in Command Log (default true)

File Input Types

TypeExampleSource
Path string'cypress/fixtures/file.json'Relative to project root
Alias'@fixtureAlias'From cy.fixture().as()
BufferCypress.Buffer.from('text')In-memory content
Object{ contents, fileName, mimeType }Full control over metadata

Action Modes

ModeSubjectEvents Fired
'select' (default)<input type="file"> or associated <label>change
'drag-drop'Any DOM element or cy.document()dragenter, dragover, drop

Object Properties

PropertyRequiredPurpose
contentsYesFile body (Buffer, string, or object)
fileNameNoName the app sees; defaults to path filename or empty
mimeTypeNoType for validation; inferred from extension
lastModifiedNoTimestamp; 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

PitfallWhy It HappensFix
selectFile throws on a divUsed default select mode on non-inputAdd { action: 'drag-drop' }
File not found errorPath not relative to project rootUse cypress/fixtures/... prefix
MIME type rejectedmimeType omitted and extension unknownSupply mimeType explicitly
Drop event not firingTarget element covered by overlayAdd { force: true } or fix z-index
Alias not resolvingFixture not loaded before useCall cy.fixture().as() first
Chained assertion failsSubject unreliable after selectFileAssert 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

ItemValue
Commandcy.selectFile(file, options?)
Default mode'select' โ€” sets files on an input
Drag mode'drag-drop' โ€” fires drag event sequence
Disk pathRelative to project root
Alias'@fixtureName' from cy.fixture().as()
In-memory contentCypress.Buffer.from(...) or { contents }
MIME typeOptional; inferred from extension
Multi-filePass an array
Clear selectionselectFile([])
Migration sourceReplaces cypress-file-upload plugin

Key takeaways:

  • Two modes solve two problems. 'select' mode handles standard file inputs by setting the files property and firing change. '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 containing cypress.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, supply mimeType explicitly. 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: attachFile becomes selectFile, filePath becomes contents, and subjectType: 'drag-drop' becomes action: '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.

Was this helpful?


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!