How to Upload File in Cypress: Simple Guide with Example
To upload a file in Cypress, use the
cypress-file-upload plugin which adds the attachFile command. Install the plugin, import it in your support file, then use cy.get('input[type=file]').attachFile('filename') to simulate file upload in your test.Syntax
The basic syntax to upload a file in Cypress using the cypress-file-upload plugin is:
cy.get(selector): Selects the file input element..attachFile(filename, options): Attaches the file to the input.filenameis the file path relative to thecypress/fixturesfolder.
javascript
cy.get('input[type=file]').attachFile('example.json')
Example
This example shows how to upload a file named example.json located in the cypress/fixtures folder to a file input on a webpage.
javascript
import 'cypress-file-upload'; describe('File Upload Test', () => { it('uploads a file successfully', () => { cy.visit('https://example.com/upload'); cy.get('input[type=file]').attachFile('example.json'); cy.get('form').submit(); cy.contains('Upload successful').should('be.visible'); }); });
Output
Test passes if the file is uploaded and confirmation text appears.
Common Pitfalls
Common mistakes when uploading files in Cypress include:
- Not installing or importing the
cypress-file-uploadplugin. - Using incorrect file paths; files must be in
cypress/fixtures. - Trying to upload files on elements that are not
input[type=file]. - Not waiting for the upload confirmation or page response.
Example of wrong and right usage:
javascript
// Wrong: Missing plugin import cy.get('input[type=file]').attachFile('example.json'); // Right: Import plugin first import 'cypress-file-upload'; cy.get('input[type=file]').attachFile('example.json');
Quick Reference
| Step | Description |
|---|---|
| Install plugin | Run npm install --save-dev cypress-file-upload |
| Import plugin | Add import 'cypress-file-upload' in cypress/support/e2e.js |
| Place file | Put file inside cypress/fixtures folder |
| Use command | cy.get('input[type=file]').attachFile('filename') |
| Assert upload | Check UI or server response after upload |
Key Takeaways
Install and import the cypress-file-upload plugin before using attachFile.
Files to upload must be placed in the cypress/fixtures folder.
Use cy.get() to select the file input and attachFile() to upload the file.
Always assert the upload success by checking UI or server response.
Avoid uploading on non-file input elements and ensure correct file paths.