Cypress File Upload - How to Handle with Different Types

Will discuss in this article how you can handle uploading different file types using plugin called cypress-file-upload which support many extension/encoding and can upload multiple files through UI and API also, this plugin can be find in cypress Plugins as shown below

let's start to install the plugin, go to terminal and pass the command as follows

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

After installation complete, let's check dependency in package.json file and it's version number

Now, we need to import this node package in commands.js as follow

Then use .attachFile() method to write your test like,

``

As you see, we have here many options to use for this function, so let's go in details to understand how we can use them

==> fixture can be a string path (or array of those), or object (or array of those) that represents your local fixture file and contains following properties:

  • {string} filePath - file path (with extension)
  • {string} fileName - the name of the file to be attached, this allows to override the name provided by filePath
  • {Blob} fileContent - the binary content of the file to be attached
  • {string} mimeType - file MIME type. By default, it gets resolved automatically based on file extension. Learn more about mime
  • {string} encoding - normally cy.fixture resolves encoding automatically, but in case it cannot be determined you can provide it manually. For a list of allowed encodings, see here

==> processingOpts contains following properties:

  • {string} subjectType - target (aka subject) element kind: 'drag-n-drop' component or plain HTML 'input' element. Defaults to 'input'
  • {boolean} force - same as for cy.trigger, it enforces the event triggers on HTML subject element. Usually this is necessary when you use hidden HTML controls for your file upload. Defaults to false
  • {boolean} allowEmpty - when true, do not throw an error if fileContent is zero length. Defaults to false

Finally, after passing the right options for your case, check the test running, will be like this

Now, it's your turn, do some practice with different test scenarios by yourself using this website 'https://the-internet.herokuapp.com/upload'

To check code, you can visit or clone this repo https://github.com/MohmedEmad/demo-cypress

There is few open bugs, you can check if you face any of them or create new one
https://github.com/abramenal/cypress-file-upload/issues


References: