0
0
CypressHow-ToBeginner ยท 4 min read

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. filename is the file path relative to the cypress/fixtures folder.
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-upload plugin.
  • 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

StepDescription
Install pluginRun npm install --save-dev cypress-file-upload
Import pluginAdd import 'cypress-file-upload' in cypress/support/e2e.js
Place filePut file inside cypress/fixtures folder
Use commandcy.get('input[type=file]').attachFile('filename')
Assert uploadCheck 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.