Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test file inputs with Cypress?

How can I write an e2e test of flow that requires interaction with the file Input DOM element?

If it's a text input I can interact with it (check value, set value) etc as its a DOM component. But If I have a File Input element, I am guessing that the interaction is limited till I can open the dialog to select a File. I can't move forward and select the file I want to upload as the dialog would be native and not some browser element.

So how would I test that a user can correctly upload a file from my site? I am using Cypress to write my e2e tests.

like image 619
sidoshi Avatar asked Nov 02 '17 11:11

sidoshi


People also ask

What is blob in Cypress?

Cypress automatically includes a Blob library and exposes it as Cypress. Blob . Use Cypress. Blob to convert base64 strings to Blob objects.


2 Answers

it('Testing picture uploading', () => {     cy.fixture('testPicture.png').then(fileContent => {         cy.get('input[type="file"]').attachFile({             fileContent: fileContent.toString(),             fileName: 'testPicture.png',             mimeType: 'image/png'         });     }); }); 

Use cypress file upload package: https://www.npmjs.com/package/cypress-file-upload

Note: testPicture.png must be in fixture folder of cypress

like image 144
Muhammad Bilal Avatar answered Sep 17 '22 23:09

Muhammad Bilal


For me the easier way to do this is using this cypress file upload package

Install it:

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

Then add this line to your project's cypress/support/commands.js:

import 'cypress-file-upload'; 

Now you can do:

const fixtureFile = 'photo.png'; cy.get('[data-cy="file-input"]').attachFile(fixtureFile); 

photo.png must be in cypress/fixtures/

For more examples checkout the Usage section on README of the package.

like image 20
Lucas Andrade Avatar answered Sep 20 '22 23:09

Lucas Andrade