0
0
Cypresstesting~5 mins

File upload (cy.selectFile) in Cypress

Choose your learning style9 modes available
Introduction

We use file upload testing to check if a website correctly accepts and processes files from users.

Testing a form where users upload profile pictures.
Checking if a document upload feature works on a job application site.
Verifying that a website accepts and reads CSV files for data import.
Ensuring that drag-and-drop file upload areas handle files properly.
Syntax
Cypress
cy.get('input[type=file]').selectFile('path/to/file')

Use a CSS selector to find the file input element.

The file path is relative to the Cypress project root or absolute.

Examples
Selects a PNG file from the fixtures folder to upload.
Cypress
cy.get('input[type=file]').selectFile('cypress/fixtures/sample.png')
Uploads a PDF file using an element with id 'upload'.
Cypress
cy.get('#upload').selectFile('cypress/fixtures/document.pdf')
Uploads a file created from text content directly in the test.
Cypress
cy.get('input[type=file]').selectFile({ contents: Cypress.Buffer.from('Hello') })
Sample Program

This test visits a page with a file upload form, selects a sample image file, submits the form, and checks for a success message.

Cypress
describe('File Upload Test', () => {
  it('uploads a sample image file', () => {
    cy.visit('https://example.com/upload')
    cy.get('input[type=file]').selectFile('cypress/fixtures/sample.png')
    cy.get('form').submit()
    cy.contains('Upload successful').should('be.visible')
  })
})
OutputSuccess
Important Notes

Always keep test files in the cypress/fixtures folder for easy access.

Use cy.selectFile to simulate real user file selection without UI interaction.

Check that the file input element is visible and enabled before selecting a file.

Summary

File upload testing ensures your site handles user files correctly.

cy.selectFile lets you pick files in tests easily.

Keep test files organized and verify upload success messages.