Open In App

How to test file inputs with Cypress?

Last Updated : 08 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

File uploads are a common feature in many web applications, allowing users to submit documents, images, and other types of files. Testing these functionalities is crucial to ensure a smooth user experience and to verify that the application handles files correctly. Cypress, a popular end-to-end testing framework, provides an intuitive way to test file inputs. With its powerful commands and easy setup, you can simulate user interactions with file uploads and validate the application’s response.

This guide will walk you through the process of testing file inputs using Cypress, providing an example, and outlining the expected outcomes. Whether you're new to Cypress or looking to enhance your testing strategies, this guide will equip you with the knowledge needed to effectively test file uploads in your applications.

Set up Cypress for Automation

Step 1. Initialize Project

First, check that you have a package.json file in your project folder by running this command.

npm init -y

Step 2. Install Cypress

If you don’t have cypress installed, then install it with this command

npm install cypress@"Version"

Step 3: Set Up Cypress Commands

In cypress/support/commands.js,import the cypress-file-upload plugin:

import 'cypress-file-upload';

Step 4: Create a Test File

In the cypress/fixtures/ folder, add a file (e.g., file.txt):

This is a sample file for  GeeksForGeeks testing.

Step 5: Install the cypress-file-upload

Cypress doesn’t natively support file uploads, so you need to install the cypress-file-upload plugin.

Run this command in your project:

npm install --save-dev cypress-file-upload

Step 6. Open Cypress

open the Cypress Test Runner with:

npx cypress open

Folder Structure

folder structure
Folder Structure of the project

Example to test file inputs with Cypress

In this example, Test a basic file upload feature in a web application using Cypress. The example assumes that there is a simple form on the page where users can upload a file, such as a text document.

JavaScript
// file_upload.spec.cy.js
describe("File Upload Test", () => {
    it("should upload a file successfully", () => {
        // Visit the page
        cy.visit(
            "http://127.0.0.1:8000"); // Replace with your
                                      // actual page URL

        // Define the file to upload from the fixtures
        // folder
        const fileName = "file.txt"; // The file exists in
                                     // the fixtures folder

        // Wait for the file input element to be visible and
        // attach the file
        cy.get("input[type=\"file\"]", {
              timeout : 10000
          }) // Increase timeout to 10 seconds
            .should("be.visible") // Check if the file input
                                  // is visible
            .attachFile(fileName, {
                force : true
            }); // Force file upload if input is hidden

        // Optional: Assert that the file input contains the
        // selected file
        cy.get("input[type=\"file\"]")
            .should("have.value",
                    "C:\\fakepath\\file.txt"); // Fake path
                                               // is used in
                                               // browsers

        // Optional: Add additional checks to confirm the
        // upload (e.g., uploaded file name in UI)
        // cy.get('.uploaded-file-name').should('contain',
        // 'file.txt');  // Example assertion
        cy.get("#fileUpload")
            .attachFile(fileName); // Using the ID for the
                                   // file input
    });
});

In the actule page URL http://127.0.0.1:8000/

The HTML looks like:

HTML
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
    </head>
    <body>
        <h1>Hello GFG</h1>
        <input id="fileUpload" type="file" class="custom-class">
        <script src="" async defer></script>
    </body>
</html>

Output:

ss
Output

Conclusion

In conclusion, testing file uploads is crucial for ensuring a smooth user experience in web applications, and Cypress simplifies this process with its intuitive commands. This guide demonstrated how to simulate file selection, submit a form, and verify successful uploads, providing a solid foundation for testing. By incorporating such tests, you can identify issues early and ensure your application handles files correctly, ultimately enhancing reliability and user satisfaction. As you expand your testing strategy, consider exploring Cypress's advanced features to further strengthen your application's functionality.


Next Article
Article Tags :

Similar Reads