Cypress - File Upload

Last Updated : 22 Aug, 2024

Cypress is an open-source website testing tool that is used to automate tests for JavaScript web applications. It is designed for end-to-end testing and it can be used for Unit tests and Integration tests as well. It is fast, reliable, and can run in real-time directly in the browser.

It's built to work with any front-end framework or website, including React, Angular, and Vue. In this article, we will learn about File Upload in Cypress.

File Upload in Cypress

To test file uploads in Cypress, you can use the .selectFile(file) function provided by the cypress which will allow you to select and upload the file within your tests. This capability is essential for ensuring that your web application correctly handles different file types, sizes, and potential errors during the upload process. It allows you to choose different options from where you can choose the actions (select, drag-and-drop), content type, reading Buffer, etc. You can select single and multiple files.

Syntax:

JavaScript
//Single File
 cy.get('#fileInput').selectFile(fileName);

//Multiple FIles
 cy.get('#fileInput').selectFile([fileName, fileName, fileName]);

//Options
cy.get('#fileInput').selectFile({
  contents: Cypress.Buffer.from('file contents'),
  fileName: 'file.txt',
  mimeType: 'text/plain',
  lastModified: Date.now(),
})

Importance of File Upload in Web Testing

  • User Experience: File uploads are a common feature in web applications so testing this functionality to ensures that users can upload files without issues.
  • Functionality Verification: It's essential to verify that the file upload feature works correctly under various conditions—different file types, sizes, and content.
  • Error Handling: Proper file upload testing checks how the system handles errors such as invalid file types, oversized files or interrupted uploads.
  • Security: File uploads can be a vector for security vulnerabilities such as malicious file uploads. Testing helps ensure that the application has security measures in place to protect against threats like malware or unauthorized access
  • Performance: Testing helps assess how the file upload feature performs under stress, including how it handles large files or high volumes of uploads.

Why use Cypress for File Upload Testing?

  • End-to-End Testing: Cypress provides end-to-end testing capabilities that allows you to test file uploads as part of a complete user workflow.
  • Real Browser Interaction: Cypress runs tests directly in the browser which provides more accurate representation of how file uploads will behave in a real-world scenario.
  • Easy File Handling: Cypress simplifies the process of working with file uploads by offering built-in commands and plugins that handle file interactions.
  • Automatic Waiting: Cypress automatically waits for commands and assertions to complete which reduces the need for manual waits or timeouts.
  • Clear and Reliable Debugging: Cypress provides detailed error messages and a powerful debugging toolset.

Setting up Cypress for File Upload

Before we begin make sure node.js is installed in your system.

Step 1: Create a Project Folder and move to it by using the following command.

mkdir cypress 
cd cypress

Step 2: Initialize a project and Install Cypress.

npm init -y 
npm install cypress --save-dev

Dependencies

"devDependencies": {
"cypress": "^13.13.1"
}

Step 3: After Creating a Project, Run this command to start cypress.

npx cypress open

Step 4: Testing type, Configuration and creating a spec.

  • Choose a E2E Testing or Component Testing, then after quick configuration choose browser.
  • After that create a new spec then click on your spec name to open your spec in any IDE.

Step 5: Testing HTML File.

  • Create a HTML File and open it with any live server extension.
  • Copy that live server file serve link, for later use.

Example

The below example demonstrate the file uploading in cypress.

HTML
<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Login Form</title>
</head>
<body>
  <h1>File Upload</h1>
  <form id="uploadForm">
    <input type="file" id="fileInput" />
    <button type="submit">Upload</button>
  </form>
  
  <div id="uploadMessage" style="display: none;">
    <p>Upload successful!</p>
    <p id="fileName"></p>
  </div>
  
  <script>
    document.getElementById('uploadForm').addEventListener('submit', function (e) {
      e.preventDefault();
      
      const fileInput = document.getElementById('fileInput');
      const file = fileInput.files[0];
      
      if (file) {
        // Display the success message and file name
        document.getElementById('uploadMessage').style.display = 'block';
        document.getElementById('fileName').textContent = `File Name: ${file.name}`;
      }
    });
  </script>
  
  
</body>
</html>
JavaScript
//File path : cypress/e2e/geeksforgeeks.cy.js

describe('Multiple File Upload Test', () => {
  it('should upload multiple files successfully', () => {
    cy.visit('http://127.0.0.1:5500/index.html');
    
    const fileName = 'temp.txt' //You can also pass array 

    // Attach file to the input element
    cy.get('#fileInput').selectFile(fileName);

    cy.get('form').submit();

    cy.contains('Upload successful!').should('be.visible');
    cy.get('#fileName').should('have.text', `File Name: ${fileName}`);
  });
});

Output

Best Practices for Cypress Test File Upload

Use Fixture Files for Consistency

Cypress allows you to use fixture files. It is a predefined files stored in the cypress/fixtures folder. Using fixture files ensures consistency across tests as you always use the same file content and structure.

JavaScript
it('should upload a valid file', () => {
  cy.visit('/upload');
  cy.get('input[type="file"]').selectFile('cypress/fixtures/valid-file.pdf');
  cy.get('.file-list').should('contain', 'valid-file.pdf');
});

Test Different File Types and Sizes

Ensure your application handles various file types and sizes including those that are valid and invalid, according to your application’s requirements.

JavaScript
it('should display an error for an oversized file', () => {
  cy.visit('/upload');
  cy.get('input[type="file"]').selectFile('cypress/fixtures/large-file.zip');
  cy.get('.error-message').should('contain', 'File size exceeds the limit');
});

Simulate Real User Interactions

Users interact with file uploads in various ways, such as drag-and-drop, multiple file selections, or canceling uploads. Simulating these interactions ensures your tests cover real-world scenarios.

JavaScript
it('should upload a file', () => {
  cy.visit('/upload');
  cy.get('input[type="file"]').selectFile('cypress/fixtures/file.json', { action: 'drag-drop' });
  cy.get('.success-message').should('contain', 'File Uploaded Successfully');
});

Conclusion

In conclusion, Cypress is an end-to-end automated testing tool that enables efficient and reliable testing of web applications. Cypress provides selectFile function to upload single and multiple file. Cypress commands are easy-to-write that make it an ideal choice for automating the testing of elements and other web components.

Comment

Explore