The Talent500 Blog
Cypress Basics: Uploading A File 1

Cypress Basics: Uploading A File

There are several methods for uploading files, but they all have a few characteristics in common. Most significantly, while dealing with file upload, we must have our frontend ready to take the file and our backend ready to manage it. Let’s start with the frontend and how we can use Cypress to create an upload.


What is Cypress?

Cypress is a free and open-source test automation tool. It may be used to automate front end and application programming interface (API) testing.

 

Uploading a file with Cypress

Start with version 9.3.0. A .selectFile() command Cypress handles all the file uploads you’ll need. It is easy in usage:

cy.get(‘#upload’)

.selectFile(‘cypress/fixtures/logo.png’)

So, which element must we choose? This is where we get to delve a bit further into the code. When you upload something, an input type=file> element appears on the page. Even if you don’t see it, I guarantee you that it exists. It’s an HTML5 element that gives your application an API that allows it to interface with your browser and open the “select file” window. This is how this element appears on the page in most cases:

Cypress Basics: Uploading A File 2However, while using Cypress, we do not click this button, but rather pick the <input> element and utilize the .selectFile() method on it. Instead of engaging with a dialog window to choose a file, we just give the path of the file we wish to upload. But what if there is no “Choose file” option, but instead an upload button or a dropzone area?


Uploading files to a dropzone

Many pages opt for a little richer UI in which the client may simply drag and drop a file or click a neatly designed button. This may be anything like:

Cypress Basics: Uploading A File 3In situations like these, the <input> element is frequently hidden. The fascinating part is that the <input> element can be in unexpected places in the DOM, typically outside of the dropzone area. This is because JavaScript handles the file insertion. Imagine your file being grabbed from the dropzone and sent into the <input> element, where it is processed.

The dropzone looks something like this in the project:

Cypress Basics: Uploading A File 4You’ll see that the <input> element has a style of display: none and therefore is hidden from the user. We can choose one of the three strategies to upload a file to this dropzone: 

First strategy:

// input is invisible, so we need to skip Cypress UI checksst 

cy.get(‘input[type=file]’)

.selectFile(‘cypress/fixtures/logo.png’, { force: true })

 Second strategy:

// make our input visible by invoking a jQuery function to it

cy.get(‘input[type=file]’)

.invoke(‘show’)

.selectFile(‘cypress/fixtures/logo.png’)


Third strategy:


// use Cypress’ ability to handle dropzones

cy.get(‘[data-cy=upload-image]’)

.selectFile(‘cypress/fixtures/logo.png’, { action: ‘drag-drop’ })

 

In the final example, notice how we choose the whole dropzone rather than just the <input> element. This is significant since there is a distinction between the two tactics. If we choose the incorrect element, we may receive the following message: cy.selectFile() can only be called on an input type=”file”> or a label for=”fileInput”> referring to or containing one.


The second half of this scenario takes place when our photograph is transmitted to the server. Our frontend may handle picture uploads in a variety of methods, therefore there may be some minor variances in how file uploads are handled in your application, but the overall concept is as follows:

 

cy.fixture(‘logo.png’, ‘binary’).then( image => {

  const blob = Cypress.Blob.binaryStringToBlob(image, ‘image/png’);

  const formData = new FormData();

  formData.append(‘image’, blob, ‘logo.png’);

    cy.request({

      method: ‘POST’,

      url: ‘/api/upload’,

      body: formData,

      headers: {

        ‘content-type’: ‘multipart/form-data’

      },

})

 

Our input <type=file> element is often seen in an <html form>. In most cases, the <form> element comprises numerous <input> elements. FormData interface handles them before sending them to the API. Essentially, each piece of data is appended to the FormData object before being sent to the server through API.

 

In Cypress, we must manually build this FormData and attach our picture to it. As you may have observed, we are processing the picture before we.append() it to the FormData object. This occurs in two ways:

 

  1. Using binary encoding, we load our image as a fixture, using binary encoding
  2. Converting this binary encoded image to Blob

Blob is an abbreviation for “binary large object,” which means we are transforming our image into text. This is generally handled by our front-end application. We need to execute this manually in the Cypress test because we are avoiding using our front end. In certain ways, our test will act similarly to our application.

 

You are now ready to contact your API once you have handled your file and filled up your FormData object. The FormData object itself will be the body of your request. The only thing left to do is include the ‘content-type’:’multipart/form-data’ header to let the server know you’re submitting this sort of request.
As previously said, the ultimate solution for uploading a file through API will depend on the API and the application you are testing, but the fundamental idea should be similar to the example given above.

Keynote:

Cypress is an excellent tool for individuals who wish to quickly develop relevant end-to-end tests. It also makes debugging difficulties very simple thanks to its live display, photos, videos, and pictures. Cypress gives you a visual interface as a test script writer to show if the test instructions were successfully run, succeeded, or failed. Similarly, it employs a locator to identify the UI parts of the application to be evaluated. When run via the command line interface, it may also record a video of the whole test suite execution.

0
Afreen Khalfe

Afreen Khalfe

A professional writer and graphic design expert. She loves writing about technology trends, web development, coding, and much more. A strong lady who loves to sit around nature and hear nature’s sound.

Add comment