October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Cypress

How to Upload Files to Hidden File Inputs in Cypress

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Cypress’s built-in selectFile() command and force the action when the native input is hidden:

cy.get('input[type="file"]')
  .selectFile('cypress/fixtures/file.json', { force: true })

The path is relative to your Cypress project root, and the file must exist. This supplies the file to the DOM input; you still need an assertion that your application processed the upload.

Why hidden inputs need force: true

Modern upload controls commonly hide the native <input type="file"> and expose a styled button or drop zone instead. Cypress documents this pattern in the selectFile() API reference.

By default, Cypress applies actionability checks before interacting. A hidden input fails visibility checks, so pass { force: true } when your test’s purpose is to attach a file directly. Forced actions skip checks for visibility, disabled state, DOM attachment, animation and covering elements; they also do not scroll the element into view. These details are described in Cypress’s interaction guide.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Lexar D40E 128GB Dual USB 3.2 Gen 1 Type-C Jump Drive, Champagne Silver
  • USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
  • Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
  • Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
  • Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
  • Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty

Forcing the input proves that your test supplied a file to the page. It does not prove that a real user can click the visible button, that the picker opens, or that the server accepted the upload. Test those user-facing behaviors separately when they matter.

Basic hidden-input upload

  1. Put a deterministic test file under your project, commonly in cypress/fixtures/.
  2. Locate the file input with a stable selector.
  3. Call selectFile() with the fixture path and force: true.
  4. Assert on the application result, such as a filename, preview, success message or completed request.
describe('document upload', () => {
  it('uploads a PDF through the hidden input', () => {
    cy.visit('/documents/new')

    cy.get('input[type="file"]')
      .selectFile('cypress/fixtures/report.pdf', { force: true })

    cy.get('[data-cy="upload-success"]')
      .should('be.visible')
      .and('contain', 'report.pdf')
  })
})

A path is preferable when the file exists on disk because Cypress attaches the file as it is stored, avoiding accidental text encoding changes.

Choose a selector that identifies the correct input

Use a dedicated data-cy or data-testid attribute when possible. A generic input[type="file"] selector is fine for a page with one input, but it can select the wrong control when a form contains several upload fields.

cy.get('[data-cy="avatar-input"]')
  .selectFile('cypress/fixtures/avatar.png', { force: true })

The default selection action requires exactly one file input or a label associated with one. If your selector matches multiple elements, narrow it with a field-specific attribute, .first() or a container scope, and confirm that the resulting test describes the intended control.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use fixtures, aliases and in-memory files

Binary fixture through an alias

When loading a binary fixture first, specify a null encoding so Cypress does not interpret the bytes as text:

cy.fixture('report.pdf', null).as('report')

cy.get('input[type="file"]')
  .selectFile('@report', { force: true })

This is useful when a test reuses the same fixture or needs to prepare it before selection.

Rank #2
SANDISK 128GB Ultra Flair, USB-A Flash Drive, Up to 150MB/s Read Speeds
  • High-speed USB 3.0 performance of up to 150MB/s(1) [(1) Write to drive up to 15x faster than standard USB 2.0 drives (4MB/s); varies by drive capacity. Up to 150MB/s read speed. USB 3.0 port required. Based on internal testing; performance may be lower depending on host device, usage conditions, and other factors; 1MB=1,000,000 bytes]
  • Transfer a full-length movie in less than 30 seconds(2) [(2) Based on 1.2GB MPEG-4 video transfer with USB 3.0 host device. Results may vary based on host device, file attributes and other factors]
  • Transfer to drive up to 15 times faster than standard USB 2.0 drives(1)
  • Sleek, durable metal casing
  • Easy-to-use password protection for your private files(3) [(3)Password protection uses 128-bit AES encryption and is supported by Windows 7, Windows 8, Windows 10, and Mac OS X v10.9 plus; Software download required for Mac, visit the SanDisk SecureAccess support page]

Construct file contents in the test

The object form accepts contents and optional metadata. Cypress can infer the MIME type from the filename extension; provide mimeType explicitly when the extension is ambiguous or absent.

cy.get('input[type="file"]').selectFile({
  contents: Cypress.Buffer.from('file contents'),
  fileName: 'report.txt',
  mimeType: 'text/plain',
  lastModified: Date.now(),
}, { force: true })

fileName, mimeType and lastModified are optional. If Cypress cannot infer a type, the MIME value may be empty, so set it when your application validates it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Select several files

Multiple selection only works when the input has the HTML multiple property. Select the input specifically marked for multiple files:

cy.get('input[type="file"][multiple]')
  .selectFile([
    'cypress/fixtures/one.txt',
    'cypress/fixtures/two.txt',
  ], { force: true })

If the input does not permit multiple files, Cypress reports a failure instead of silently changing the application’s behavior.

Test a drag-and-drop upload zone

A drop zone is a different interaction from selecting a hidden input. Use action: 'drag-drop' on the visible drop target (or on the document), rather than forcing the hidden input:

cy.get('[data-cy="drop-zone"]').selectFile(
  'cypress/fixtures/report.pdf',
  { action: 'drag-drop' },
)

In drag-drop mode the subject can be any DOM element or the document. In the default selection mode it must be one file input or an associated label. Choose drag-drop when the behavior you need to cover is the zone’s drag events, highlighting and drop handling.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
2 Pack 64GB USB Flash Drive USB 2.0 Thumb Drives Jump Drive Fold Storage Memory Stick Swivel Design - Black
  • What You Get - 2 pack 64GB genuine USB 2.0 flash drives, 12-month warranty and lifetime friendly customer service
  • Great for All Ages and Purposes – the thumb drives are suitable for storing digital data for school, business or daily usage. Apply to data storage of music, photos, movies and other files
  • Easy to Use - Plug and play USB memory stick, no need to install any software. Support Windows 7 / 8 / 10 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, compatible with USB 2.0 and 1.1 ports
  • Convenient Design - 360°metal swivel cap with matt surface and ring designed zip drive can protect USB connector, avoid to leave your fingerprint and easily attach to your key chain to avoid from losing and for easy carrying
  • Brand Yourself - Brand the flash drive with your company's name and provide company's overview, policies, etc. to the newly joined employees or your customers

Assert the upload outcome, not just file selection

selectFile() changes the input’s selected files and dispatches the events your application normally handles. It does not guarantee that validation, a network request, server-side storage or post-processing succeeded. Cypress’s FAQ notes that upload behavior depends on how the application is implemented; see Cypress’s FAQ.

Pick an assertion that represents your product’s contract:

  • Client-side response: a preview image, filename chip, progress completion or enabled Submit button.
  • Validation: an expected error for an unsupported extension, size or MIME type.
  • Network behavior: intercept the upload request and assert its method, URL or response.
  • Server result: a success toast, record in a list or downloadable link visible after the request finishes.
cy.intercept('POST', '**/api/documents').as('upload')

cy.get('input[type="file"]')
  .selectFile('cypress/fixtures/report.pdf', { force: true })

cy.wait('@upload').its('response.statusCode').should('eq', 201)
cy.get('[data-cy="upload-success"]').should('be.visible')

Do not use a successful command completion as your only assertion. A file can be attached while the application rejects it later.

Common failures and fixes

Symptom Likely cause Fix
“Element is not visible” The native input is intentionally hidden. Use { force: true } after confirming that direct input selection is the behavior under test.
“Expected subject to be a file input or label” The selector targets a button, wrapper or drop zone while using the default action. Select input[type="file"] (or its associated label), or switch to { action: 'drag-drop' } for a drop target.
File not found The path is wrong or the fixture is outside the project root. Check spelling and case, and place the file under the project directory. Paths are relative to the directory containing Cypress’s default configuration file.
Multiple-file selection fails The input lacks the multiple property. Use the application’s multiple-file input or test one file at a time; do not expect Cypress to add the property.
Binary file is corrupted A fixture was read using text encoding. Load it with cy.fixture('name', null), or pass its path directly.
Selection succeeds but no upload occurs The application requires a change event, a separate submit action, validation, or a network response. Assert the UI flow and request, and perform the required submit or continue action.
Timed-out command The input, alias or file path was not available before Cypress’s timeout. Wait for the page state that creates the input, correct the selector/path, and avoid arbitrary delays when a visible condition can be asserted.

Actionability, visibility and Cypress versions

selectFile() was added in Cypress 9.3.0. The command reference records later changes, including per-axis scrollBehavior support in 15.20.0. As of Cypress 16, the default visibility algorithm delegates to the browser’s native Element.checkVisibility() API, but the hidden-input pattern still uses force: true when the input is not directly visible.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Force only the file-selection command that needs it. Keeping other interactions subject to normal actionability checks helps catch detached, covered or disabled controls. If you need to verify that a visible “Choose file” button activates the picker, write a separate test for that user-facing control instead of treating a forced selection as proof.

Should you use a plugin or another upload helper?

For current Cypress end-to-end tests, start with the built-in command. Cypress describes the older cypress-file-upload package as deprecated; the built-in command drew heavy inspiration from it and removes the extra dependency for this use case.

Rank #4
SIMMAX 32GB Memory Stick USB 2.0 Flash Drives Swivel Thumb Drive Pen Drive (32GB Purple)
  • GOOD VALUE PACKAGE - 1 Pack 32GB Memory Stick USB 2.0 Flash Drives with great cost performance and high quality.
  • BIG CAPACITY - The available capacity: 29.10GB-29.8GB, You can save the data of movies, music, photos, designs, programs, manuals, handouts in a high speed.Good performance in digital data storing, transferring and sharing with families, friends, workmates, clients and machines.
  • EASY TO USE & PLUG AND WORK - Support windows 7 / 8 / 10 / Vista / XP / 2000 / ME / NT Linux and Mac OS, Compatible with USB2.0 and below.
  • TWISTTURN DESIGN & EASY CARRY - The metal clip rotates 360° round the ABS plastic body which with rubber oil skin feeling finish. The capless design can avoid lossing of cap, and providing efficient protection to the USB port.
  • WARRANTY & SUPPORT - SIMMAX logo is laser printed on the USB connector surface, our products are of good quality and we promise that any problem about the product within one year since you buy.

Testing Library’s user-event v13 upload helper belongs to a different testing layer. It is not a Cypress command, so do not mix its API into a Cypress chain.

Keep uploads deterministic and maintainable

  • Check fixture files into version control and use small, purpose-built files for fast tests.
  • Use stable test selectors instead of CSS classes that describe presentation.
  • Give each test a clear file purpose, such as valid-pdf.pdf or too-large.zip.
  • Test accepted and rejected files separately so a failure identifies the validation rule that changed.
  • Stub or isolate external storage when the goal is client-side behavior; use a dedicated integration test when the goal is the real backend.
  • Wait on a meaningful UI state or intercepted request rather than adding a fixed sleep.

These practices keep a forced hidden-input interaction focused: attach known bytes, observe the application’s response and report failures at the layer that actually broke.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your next step is to capture a visual record of an upload-result page rather than exercise the upload itself, ScreenshotNeo can return a screenshot or PDF through one HTTP request. It is a website screenshot API, not a replacement for Cypress’s file-selection assertions. Before capture, it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets; each step can be disabled. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. An MCP server also lets Claude, Cursor and other MCP clients call take_screenshot, get_page_info and capture_pdf.

Use the documented endpoint and options at ScreenshotNeo’s API documentation:

curl -G "https://api.screenshotneo.com/v1/shot" 
  -d access_key=YOUR_API_KEY 
  --data-urlencode url=https://stripe.com 
  -o shot.webp

The same request in Python:

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

And in Node.js:

const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com',
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

ScreenshotNeo includes full-page and element capture, device presets and custom viewports, retina scale, PDF controls, custom CSS and JavaScript, waits, request blocking, headers, cookies, user agents, timezone and geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous webhooks, bulk capture and a usage API. Every feature is on every plan. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots, with yearly billing providing two months free.

Try ScreenshotNeo free at https://screenshotneo.com/account/sign-up/.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Bottom line

For a hidden Cypress file input, call selectFile() with a project-relative path and { force: true }. Use an array only with an input that has multiple, use drag-drop mode for a drop zone, and always assert the application-visible or network result that demonstrates the upload actually worked.

Best Value
Sale
IMEASON Swivel Design 16GB USB Flash Drive with Keychain, USB 2.0 Portable Thumb Drive Memory Stick, FAT32 Format Flashdrive for Data Storage, Photos, Music, Files (Black, 16 GB)
  • 【16GB Flash Drive】USB flash drives with 16GB capacity, meet your needs of daily use on work, school, home and travelling for photos, music, videos, files storage and transfer. IMEASON thumb drives can be used to store different files, easy to data backup.
  • 【Metal Swivel Cap Design】USB thumb drive is metal swivel cover provides extra protection for the usb thumbdrive connector, no usb drive cap to lose; keychain design makes it easier to carry without worrying lose it.
  • 【Wide Compatibility】USB drive supports Windows 7/8/10/11 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, also Supports USB 2.0 and 1.1 ports. USB Stick support TV, desktop, notebook computer, car, audio and other device. The USB Memory Stick is your great data storage and transfer companion with traveling and working.
  • 【Easy to use】usb memory stick is plug and play without any software installation. Just simply plug the Flashdrive into the port of your USB-compatible devices such as computer, laptop to start data storage or transmission.
  • 【What You Get】16 GB USB Flash Drive Thumb Drive, The default format of the usb storage flash drive is FAT32.

Frequently Asked Questions

Can Cypress upload to an input with display: none?

Yes. Target the native file input and pass { force: true } to bypass visibility actionability checks.

Does force: true verify that a user can open the file picker?

No. It attaches the file directly. Test the visible picker button separately if that interaction is part of your requirements.

What path should I pass to selectFile()?

Use a path relative to the Cypress project root, normally the directory containing your Cypress configuration file, such as cypress/fixtures/report.pdf.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I upload several files?

Pass an array of paths and select an input with the HTML multiple property.

Is cypress-file-upload still required?

No. Cypress’s built-in selectFile() command is the recommended starting point for current tests; the package is deprecated.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.