All Projects → javieraviles → cypress-upload-file-post-form

javieraviles / cypress-upload-file-post-form

Licence: MIT license
Solution for two Cypress testing use-cases I came across with: perform a direct http FORM request to the server containing a file and other parameters and upload a file into a form before submission

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to cypress-upload-file-post-form

image-uploader
Simple Drag & Drop image uploader plugin to static forms, without using AJAX
Stars: ✭ 70 (+18.64%)
Mutual labels:  file-upload, form, post
dropzone-ui-react
The most complete React Library Component for drag’n’drop files. Image and video previews. File validation. Multilanguage. Server side support.
Stars: ✭ 122 (+106.78%)
Mutual labels:  file-upload, form, form-data
cypress-xpath
Adds XPath command to Cypress test runner
Stars: ✭ 145 (+145.76%)
Mutual labels:  cypress, cypress-io
cygger
Boilerplate generator for API Testing from Swagger to Cypress
Stars: ✭ 20 (-66.1%)
Mutual labels:  api-testing, cypress
quasar-testing
Testing Harness App Extensions for the Quasar Framework 1.0+
Stars: ✭ 142 (+140.68%)
Mutual labels:  cypress, e2e-testing
EasyForm-Android
该项目是一个android端用于生成复杂表格的库。可以用来做像Excel表格那样的UI界面。
Stars: ✭ 17 (-71.19%)
Mutual labels:  excel, form
Filecontextcore
FileContextCore is a "Database"-Provider for Entity Framework Core and adds the ability to store information in files instead of being limited to databases.
Stars: ✭ 91 (+54.24%)
Mutual labels:  excel, file
file-input-accessor
Angular directive that provides file input functionality in Angular forms.
Stars: ✭ 32 (-45.76%)
Mutual labels:  file, form
Angular File Uploader
Angular file uploader is an Angular 2/4/5/6/7/8/9/10 + file uploader module with Real-Time Progress Bar, Responsive design, Angular Universal Compatibility, localization and multiple themes which includes Drag and Drop and much more.
Stars: ✭ 92 (+55.93%)
Mutual labels:  file-upload, file
seenreq
Generate an object for testing if a request is sent, request is Mikeal's request.
Stars: ✭ 42 (-28.81%)
Mutual labels:  request, post
PHP-FileUpload
Simple and convenient file uploads — secure by default
Stars: ✭ 53 (-10.17%)
Mutual labels:  file, form
cypress-retry
Retry just the failed Cypress.io tests using Cypress module API and AST rewriting
Stars: ✭ 16 (-72.88%)
Mutual labels:  cypress, cypress-io
BulkPDF
BulkPDF is a free and easy to use open source software, which allows to automatically fill an existing PDF form with differen values. Only a spreadsheet (Microsoft Excel 2007/2010/2013, LibreOffice or OpenOffice Calc) with the desired values is required.
Stars: ✭ 94 (+59.32%)
Mutual labels:  excel, form
SwiftyExcelView
A View Look Like Excel & Form
Stars: ✭ 45 (-23.73%)
Mutual labels:  excel, form
svelte-pwa-now
A PWA ready Svelte v3.0 starter template with Tailwind, Now integration and optional Typescript suppot
Stars: ✭ 138 (+133.9%)
Mutual labels:  cypress, cypress-io
Uploadcare Widget
Uploadcare Widget, an ultimate tool for HTML5 file upload supporting multiple file upload, drag&drop, validation by file size/file extension/MIME file type, progress bar for file uploads, image preview.
Stars: ✭ 183 (+210.17%)
Mutual labels:  file-upload, file
cypress-hyperapp-unit-test
Unit test Hyperapp components using Cypress
Stars: ✭ 26 (-55.93%)
Mutual labels:  cypress, cypress-io
TLE5012-Magnetic-Angle-Sensor
This repository includes an library for Arduino for the TLE5012 Magnetic Angle Sensor with SSC interface.
Stars: ✭ 37 (-37.29%)
Mutual labels:  cypress, cypress-io
Frisbee
🐕 Modern fetch-based alternative to axios/superagent/request. Great for React Native.
Stars: ✭ 1,038 (+1659.32%)
Mutual labels:  file-upload, request
React Dropzone
Simple HTML5 drag-drop zone with React.js.
Stars: ✭ 8,639 (+14542.37%)
Mutual labels:  file-upload, file

cypress-upload-file-post-form

Solution for two Cypress testing use-cases I came across with: perform a direct http FORM request to the server containing a file and other parameters and upload a file into a form before submission. It works for excel files.

For both cases, the file to be uploaded / sent in the form will be placed in fixtures folder so it can be loaded by cypress.

To build these workarounds, I found useful these two links:

Cypress Issue #170 StackOverflow

First scenario (upload_file_to_form_spec.js):

I want to test a UI where a file has to be selected/uploaded before submitting the form.

Include the following code in your "commands.js" file within the cypress support folder, so the command cy.upload_file() can be used from any test:

Cypress.Commands.add('upload_file', (fileName, fileType = ' ', selector) => {
    cy.get(selector).then(subject => {
      cy.fixture(fileName, 'base64')
        .then(Cypress.Blob.base64StringToBlob)
        .then(blob => {
          const el = subject[0]
          const testFile = new File([blob], fileName, { type: fileType })
          const dataTransfer = new DataTransfer()
          dataTransfer.items.add(testFile)
          el.files = dataTransfer.files
        })
    })
  })

Then, in case you want to upload an excel file, fill in other inputs and submit the form, the test would be something like this:

describe('Testing the excel form', function () {
    it ('Uploading the right file imports data from the excel successfully', function() {

        const testUrl = 'http://localhost:3000/excel_form';
        const fileName = 'your_file_name.xlsx';
        const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        const fileInput = 'input[type=file]';

        cy.visit(testUrl);
        cy.upload_file(fileName, fileType, fileInput);
        cy.get('#other_form_input2').type('input_content2');
        .
        .
        .
        cy.get('button').contains('Submit').click();

        cy.get('.result-dialog').should('contain', 'X elements from the excel where successfully imported');
    })
})

Second scenario (send_form_data_with_file_in_post_request_spec.js):

I want to build up the FormData myself( new FormData(), formData.append/formData.set ) and send it directly with a POST request to the backend or submit the form with the FormData I have created.

For this case, the transmitted data must be in the same format as the form's submit(), which type is set to "multipart/form-data". Having a look at the MDN web docs to see how you can build a FormData: Using FormData Objects, and knowing that at this very moment (Cypress 2.1.0) cy.request doesn't support FormData (multipart/form-data) so we will need a XMLHttpRequest, the test can be performed as follows.

Include the following code in your "commands.js" file within the cypress support folder, so the command cy.form_request() can be used from any test:

// Performs an XMLHttpRequest instead of a cy.request (able to send data as FormData - multipart/form-data)
Cypress.Commands.add('form_request', (method, url, formData, done) => {
    const xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.onload = function () {
        done(xhr);
    };
    xhr.onerror = function () {
        done(xhr);
    };
    xhr.send(formData);
})

Then, in case you want to send the same form as before (form containing an excel file and other plain inputs) but build it by yourself and send it directly to the server, the test would be something like this:

describe('Testing the API', function () {
     
    it('Receives valid FormData and proccesses the information correctly', function () {

        /*
        The reason why this test may look a bit tricky is because the backend endpoint is expecting the 
        submission of a web Form (multipart/form-data), not just data within a POST. The "cy.request()" 
        command doesn't support sending a web Form as a body in a POST request, so the test uses a support 
        command that has been created to perform a genuine XMLHttpRequest where a web Form can be placed.
        */

        //Declarations
        const fileName = 'your_excel_file.xlsx';
        const method = 'POST';
        const url = 'http://localhost:3000/api/excel_form';
        const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        const inputContent2 = 'input_content2';
        const expectedAnswer = '{"msg":"X elements from the excel where successfully imported"}';

        // Get file from fixtures as binary
        cy.fixture(fileName, 'binary').then( (excelBin) => {

            // File in binary format gets converted to blob so it can be sent as Form data
            Cypress.Blob.binaryStringToBlob(excelBin, fileType).then((blob) => {

                // Build up the form
                const formData = new FormData();
                formData.set('file', blob, fileName); //adding a file to the form
                formData.set('input2', inputContent2); //adding a plain input to the form
                .
                .
                .
                // Perform the request
                cy.form_request(method, url, formData, function (response) {
                    expect(response.status).to.eq(200);
                    expect(expectedAnswer).to.eq(response.response);
                });
                
            })
            
        })
        
    })
      
})
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].