├── .gitignore ├── cypress.json ├── cypress ├── fixtures │ └── example.json ├── plugins │ └── index.js ├── support │ ├── index.js │ └── commands.js └── integration │ ├── upload_file_to_form_spec.js │ └── send_form_data_with_file_in_post_request_spec.js ├── LICENSE ├── package.json └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ -------------------------------------------------------------------------------- /cypress.json: -------------------------------------------------------------------------------- 1 | { 2 | "chromeWebSecurity": false 3 | } 4 | -------------------------------------------------------------------------------- /cypress/fixtures/example.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Using fixtures to represent data", 3 | "email": "hello@cypress.io", 4 | "body": "Fixtures are a great way to mock data for responses to routes" 5 | } -------------------------------------------------------------------------------- /cypress/plugins/index.js: -------------------------------------------------------------------------------- 1 | // *********************************************************** 2 | // This example plugins/index.js can be used to load plugins 3 | // 4 | // You can change the location of this file or turn off loading 5 | // the plugins file with the 'pluginsFile' configuration option. 6 | // 7 | // You can read more here: 8 | // https://on.cypress.io/plugins-guide 9 | // *********************************************************** 10 | 11 | // This function is called when a project is opened or re-opened (e.g. due to 12 | // the project's config changing) 13 | 14 | module.exports = (on, config) => { 15 | // `on` is used to hook into various events Cypress emits 16 | // `config` is the resolved Cypress config 17 | } 18 | -------------------------------------------------------------------------------- /cypress/support/index.js: -------------------------------------------------------------------------------- 1 | // *********************************************************** 2 | // This example support/index.js is processed and 3 | // loaded automatically before your test files. 4 | // 5 | // This is a great place to put global configuration and 6 | // behavior that modifies Cypress. 7 | // 8 | // You can change the location of this file or turn off 9 | // automatically serving support files with the 10 | // 'supportFile' configuration option. 11 | // 12 | // You can read more here: 13 | // https://on.cypress.io/configuration 14 | // *********************************************************** 15 | 16 | // Import commands.js using ES2015 syntax: 17 | import './commands' 18 | 19 | // Alternatively you can use CommonJS syntax: 20 | // require('./commands') 21 | -------------------------------------------------------------------------------- /cypress/integration/upload_file_to_form_spec.js: -------------------------------------------------------------------------------- 1 | // Upload an excel file, fill in other inputs and submit the form 2 | 3 | describe('Testing the excel form', function () { 4 | it ('Uploading the right file imports data from the excel successfully', function() { 5 | 6 | const testUrl = 'http://localhost:3000/excel_form'; 7 | const fileName = 'your_file_name.xlsx'; 8 | const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; 9 | const fileInput = 'input[type=file]'; 10 | 11 | cy.visit(testUrl); 12 | cy.upload_file(fileName, fileType, fileInput); 13 | cy.get('#other_form_input2').type('input_content2'); 14 | 15 | cy.get('button').contains('Submit').click(); 16 | 17 | cy.get('.result-dialog').should('contain', 'X elements from the excel where successfully imported'); 18 | }) 19 | }) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Javier Aviles 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cypress-upload-file-post-form", 3 | "version": "1.1.0", 4 | "description": "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", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "cypress run --browser chrome" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/javieraviles/cypress-upload-file-post-form.git" 12 | }, 13 | "keywords": [ 14 | "cypress", 15 | "cypress.io", 16 | "file", 17 | "file-upload", 18 | "submit", 19 | "form", 20 | "form-data", 21 | "post", 22 | "request", 23 | "http", 24 | "xmlhttprequest", 25 | "e2e-testing", 26 | "api-testing", 27 | "cypress.io" 28 | ], 29 | "author": "Javier Aviles", 30 | "license": "MIT", 31 | "bugs": { 32 | "url": "https://github.com/javieraviles/cypress-upload-file-post-form/issues" 33 | }, 34 | "homepage": "https://github.com/javieraviles/cypress-upload-file-post-form#readme", 35 | "devDependencies": { 36 | "cypress": "^2.1.0" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /cypress/support/commands.js: -------------------------------------------------------------------------------- 1 | // *********************************************** 2 | // This example commands.js shows you how to 3 | // create various custom commands and overwrite 4 | // existing commands. 5 | // 6 | // For more comprehensive examples of custom 7 | // commands please read more here: 8 | // https://on.cypress.io/custom-commands 9 | // *********************************************** 10 | // 11 | // 12 | // -- This is a parent command -- 13 | // Cypress.Commands.add("login", (email, password) => { ... }) 14 | // 15 | // 16 | // -- This is a child command -- 17 | // Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... }) 18 | // 19 | // 20 | // -- This is a dual command -- 21 | // Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... }) 22 | // 23 | // 24 | // -- This is will overwrite an existing command -- 25 | // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... }) 26 | 27 | 28 | Cypress.Commands.add('upload_file', (fileName, fileType = ' ', selector) => { 29 | cy.get(selector).then(subject => { 30 | cy.fixture(fileName, 'base64') 31 | .then(Cypress.Blob.base64StringToBlob) 32 | .then(blob => { 33 | const el = subject[0] 34 | const testFile = new File([blob], fileName, { type: fileType }) 35 | const dataTransfer = new DataTransfer() 36 | dataTransfer.items.add(testFile) 37 | el.files = dataTransfer.files 38 | }) 39 | }) 40 | }) 41 | 42 | // Performs an XMLHttpRequest instead of a cy.request (able to send data as FormData - multipart/form-data) 43 | Cypress.Commands.add('form_request', (method, url, formData, done) => { 44 | const xhr = new XMLHttpRequest(); 45 | xhr.open(method, url); 46 | xhr.onload = function () { 47 | done(xhr); 48 | }; 49 | xhr.onerror = function () { 50 | done(xhr); 51 | }; 52 | xhr.send(formData); 53 | }) 54 | -------------------------------------------------------------------------------- /cypress/integration/send_form_data_with_file_in_post_request_spec.js: -------------------------------------------------------------------------------- 1 | // Build and send a form containing an excel file and other plain inputs directly to the backend 2 | 3 | describe('Testing the API', function () { 4 | 5 | it('Receives valid FormData and proccesses the information correctly', function () { 6 | 7 | /* 8 | The reason why this test may look a bit tricky is because the backend endpoint is expecting the 9 | submission of a web Form (multipart/form-data), not just data within a POST. The "cy.request()" 10 | command doesn't support sending a web Form as a body in a POST request, so the test uses a support 11 | command that has been created to perform a genuine XMLHttpRequest where a web Form can be placed. 12 | */ 13 | 14 | //Declarations 15 | const fileName = 'your_excel_file.xlsx'; 16 | const method = 'POST'; 17 | const url = 'http://localhost:3000/api/excel_form'; 18 | const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; 19 | const inputContent2 = 'input_content2'; 20 | const expectedAnswer = '{"msg":"X elements from the excel where successfully imported"}'; 21 | 22 | // Get file from fixtures as binary 23 | cy.fixture(fileName, 'binary').then( (excelBin) => { 24 | 25 | // File in binary format gets converted to blob so it can be sent as Form data 26 | Cypress.Blob.binaryStringToBlob(excelBin, fileType).then((blob) => { 27 | 28 | // Build up the form 29 | const formData = new FormData(); 30 | formData.set('file', blob, fileName); //adding a file to the form 31 | formData.set('input2', inputContent2); //adding a plain input to the form 32 | 33 | // Perform the request 34 | cy.form_request(method, url, formData, function (response) { 35 | expect(response.status).to.eq(200); 36 | expect(expectedAnswer).to.eq(response.response); 37 | }); 38 | 39 | }) 40 | 41 | }) 42 | 43 | }) 44 | 45 | }) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cypress-upload-file-post-form 2 | 3 | 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. 4 | 5 | For both cases, the file to be uploaded / sent in the form will be placed in [fixtures](https://docs.cypress.io/api/commands/fixture.html#Syntax) folder so it can be loaded by cypress. 6 | 7 | To build these workarounds, I found useful these two links: 8 | 9 | [Cypress Issue #170](https://github.com/cypress-io/cypress/issues/170) 10 | [StackOverflow](https://stackoverflow.com/questions/47533989/upload-file-with-cypress-io-via-request) 11 | 12 | 13 | ## First scenario (upload_file_to_form_spec.js): 14 | 15 | I want to test a UI where a file has to be selected/uploaded before submitting the form. 16 | 17 | 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: 18 | 19 | ``` 20 | Cypress.Commands.add('upload_file', (fileName, fileType = ' ', selector) => { 21 | cy.get(selector).then(subject => { 22 | cy.fixture(fileName, 'base64') 23 | .then(Cypress.Blob.base64StringToBlob) 24 | .then(blob => { 25 | const el = subject[0] 26 | const testFile = new File([blob], fileName, { type: fileType }) 27 | const dataTransfer = new DataTransfer() 28 | dataTransfer.items.add(testFile) 29 | el.files = dataTransfer.files 30 | }) 31 | }) 32 | }) 33 | ``` 34 | 35 | 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: 36 | 37 | ``` 38 | describe('Testing the excel form', function () { 39 | it ('Uploading the right file imports data from the excel successfully', function() { 40 | 41 | const testUrl = 'http://localhost:3000/excel_form'; 42 | const fileName = 'your_file_name.xlsx'; 43 | const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; 44 | const fileInput = 'input[type=file]'; 45 | 46 | cy.visit(testUrl); 47 | cy.upload_file(fileName, fileType, fileInput); 48 | cy.get('#other_form_input2').type('input_content2'); 49 | . 50 | . 51 | . 52 | cy.get('button').contains('Submit').click(); 53 | 54 | cy.get('.result-dialog').should('contain', 'X elements from the excel where successfully imported'); 55 | }) 56 | }) 57 | ``` 58 | 59 | 60 | ## Second scenario (send_form_data_with_file_in_post_request_spec.js): 61 | 62 | 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. 63 | 64 | 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". 65 | Having a look at the MDN web docs to see how you can build a FormData: [Using FormData Objects](https://developer.mozilla.org/en-US/docs/Web/API/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](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest), the test can be performed as follows. 66 | 67 | 68 | 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: 69 | 70 | ``` 71 | // Performs an XMLHttpRequest instead of a cy.request (able to send data as FormData - multipart/form-data) 72 | Cypress.Commands.add('form_request', (method, url, formData, done) => { 73 | const xhr = new XMLHttpRequest(); 74 | xhr.open(method, url); 75 | xhr.onload = function () { 76 | done(xhr); 77 | }; 78 | xhr.onerror = function () { 79 | done(xhr); 80 | }; 81 | xhr.send(formData); 82 | }) 83 | ``` 84 | 85 | 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: 86 | 87 | ``` 88 | describe('Testing the API', function () { 89 | 90 | it('Receives valid FormData and proccesses the information correctly', function () { 91 | 92 | /* 93 | The reason why this test may look a bit tricky is because the backend endpoint is expecting the 94 | submission of a web Form (multipart/form-data), not just data within a POST. The "cy.request()" 95 | command doesn't support sending a web Form as a body in a POST request, so the test uses a support 96 | command that has been created to perform a genuine XMLHttpRequest where a web Form can be placed. 97 | */ 98 | 99 | //Declarations 100 | const fileName = 'your_excel_file.xlsx'; 101 | const method = 'POST'; 102 | const url = 'http://localhost:3000/api/excel_form'; 103 | const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; 104 | const inputContent2 = 'input_content2'; 105 | const expectedAnswer = '{"msg":"X elements from the excel where successfully imported"}'; 106 | 107 | // Get file from fixtures as binary 108 | cy.fixture(fileName, 'binary').then( (excelBin) => { 109 | 110 | // File in binary format gets converted to blob so it can be sent as Form data 111 | Cypress.Blob.binaryStringToBlob(excelBin, fileType).then((blob) => { 112 | 113 | // Build up the form 114 | const formData = new FormData(); 115 | formData.set('file', blob, fileName); //adding a file to the form 116 | formData.set('input2', inputContent2); //adding a plain input to the form 117 | . 118 | . 119 | . 120 | // Perform the request 121 | cy.form_request(method, url, formData, function (response) { 122 | expect(response.status).to.eq(200); 123 | expect(expectedAnswer).to.eq(response.response); 124 | }); 125 | 126 | }) 127 | 128 | }) 129 | 130 | }) 131 | 132 | }) 133 | ``` --------------------------------------------------------------------------------