In this tutorial, we will learn how to upload a file in Cypress using the cypress-file-upload NPM package. Cypress does not have a native support to do file uploads at the moment, however, this is something they plan to add in the future.
Since, we need to use a third-party library to do file upload, we will need to get that installed and setup to make it work with Cypress.
Install NPM Package
First thing you need to do is install the package —
npm install --save-dev cypress-file-upload
Setup Custom Command
cypress-file-upload library provides a custom command which we can use once we set it up. To do that, we need to import the library in the custom command file (cypress/support/commands.js) like this —
Then, make sure this
commands.js is imported in
cypress/support/index.js (it might be commented):
Upload File Test
Now, that we have installed the package, we can go ahead and start using the custom command. In the example below, I will be uploading a file on my test website.
The key thing to focus on the example above is the
.attachFile() command which is added by the helper library that we installed. It takes in a parameter i.e. the file name which should be included inside the
fixtures folder as shown below.
Working with hidden input fields
.attachFile() command would work if the
input[type=file] element is intractable. However, if the element is hidden then you will need to make necessary changes to make the element visible and intractable again. You can do that using the help of the Cypress
.invoke() function as seen below —
In this example, I am removing the hidden class using the jquery
removeClass function which is making my element intractable again.
To learn more about how to upload a file in Cypress, checkout the video below —
Hope you enjoyed reading this article!