
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
cypress-file-upload
Advanced tools
The cypress-file-upload npm package is a plugin for Cypress that allows you to easily test file upload functionality in your web applications. It simplifies the process of simulating file uploads in your end-to-end tests.
Basic File Upload
This feature allows you to attach a file to an input element of type 'file'. The 'attachFile' method takes the path to the file you want to upload.
cy.get('input[type="file"]').attachFile('path/to/file.txt');
Multiple File Upload
This feature allows you to attach multiple files to an input element of type 'file'. The 'attachFile' method takes an array of file paths.
cy.get('input[type="file"]').attachFile(['path/to/file1.txt', 'path/to/file2.txt']);
File Upload with Custom File Name
This feature allows you to upload a file with a custom file name. The 'attachFile' method takes an object with 'filePath' and 'fileName' properties.
cy.get('input[type="file"]').attachFile({ filePath: 'path/to/file.txt', fileName: 'customName.txt' });
File Upload with MIME Type
This feature allows you to specify the MIME type of the file being uploaded. The 'attachFile' method takes an object with 'filePath' and 'mimeType' properties.
cy.get('input[type="file"]').attachFile({ filePath: 'path/to/file.txt', mimeType: 'text/plain' });
The cypress-upload-file package provides similar functionality for file uploads in Cypress tests. It allows you to simulate file uploads but may have a different API and fewer customization options compared to cypress-file-upload.
File upload testing made easy.
This package adds a custom Cypress command that allows you to make an abstraction on how exactly you upload files through HTML controls and focus on testing user workflows.
The package is distributed via npm and should be installed as one of your project's devDependencies
:
npm install --save-dev cypress-file-upload
If you are using TypeScript, ensure your tsconfig.json
contains commands' types:
"compilerOptions": {
"types": ["cypress", "cypress-file-upload"]
}
To be able to use any custom command you need to add it to cypress/support/commands.js
like this:
import 'cypress-file-upload';
Then, make sure this commands.js
is imported in cypress/support/index.js
(it might be commented):
// Import commands.js using ES2015 syntax:
import './commands';
All set now! :boom:
Now, let's see how we can actually test something. Exposed command has signature like:
cySubject.attachFile(fixture, optionalProcessingConfig);
It is a common practice to put all the files required for Cypress tests inside cypress/fixtures
folder and call them as fixtures (or a fixture). The command recognizes cy.fixture
format, so usually this is just a file name.
cy.get('[data-cy="file-input"]')
.attachFile('myfixture.json');
cy.get('[data-cy="dropzone"]')
.attachFile('myfixture.json', { subjectType: 'drag-n-drop' });
cy.get('[data-cy="file-input"]')
.attachFile(['myfixture1.json', 'myfixture2.json']);
Note: in previous version you could also attach it chaining the command. It brought flaky behavior with redundant multiple event triggers, and was generally unstable. It might be still working, but make sure to use array instead.
In some cases you might need more than just plain JSON cy.fixture
. If your file extension is supported out of the box, it should all be just fine.
In case your file comes from some 3rd-party tool, or you already observed some errors in console, you likely need to tell Cypress how to treat your fixture file.
cy.get('[data-cy="file-input"]')
.attachFile({ filePath: 'test.shp', encoding: 'utf-8' });
Trying to upload a file that does not supported by Cypress by default? Make sure you pass encoding
property (see API).
Normally you do not need this. But what the heck is normal anyways :neckbeard:
If you need some custom file preprocessing, you can pass the raw file content:
const special = 'file.spss';
cy.fixture(special, 'binary')
.then(Cypress.Blob.binaryStringToBlob)
.then(fileContent => {
cy.get('[data-cy="file-input"]').attachFile({
fileContent,
filePath: special,
encoding: 'utf-8',
lastModified: new Date().getTime()
});
});
You still need to provide filePath
in order to get file's metadata and encoding. For sure this is optional, and you can do it manually:
cy.fixture('file.spss', 'binary')
.then(Cypress.Blob.binaryStringToBlob)
.then(fileContent => {
cy.get('[data-cy="file-input"]').attachFile({
fileContent,
fileName: 'whatever',
mimeType: 'application/octet-stream',
encoding: 'utf-8',
lastModified: new Date().getTime(),
});
});
cy.get('[data-cy="file-input"]')
.attachFile({ filePath: 'myfixture.json', fileName: 'customFileName.json' });
Normally you have to provide non-empty fixture file to test something. If your case isn't normal in that sense, here is the code snippet for you:
cy.get('[data-cy="file-input"]')
.attachFile({ filePath: 'empty.txt', allowEmpty: true });
Cypress' cy.wait
command allows you to pause code execution until some asyncronous action is finished. In case you are testing file upload, you might want to wait until the upload is complete:
// start watching the POST requests
cy.server({ method:'POST' });
// and in particular the one with 'upload_endpoint' in the URL
cy.route({
method: 'POST',
url: /upload_endpoint/
}).as('upload');
const fileName = 'upload_1.xlsx';
cy.fixture(fileName, 'binary')
.then(Cypress.Blob.binaryStringToBlob)
.then(fileContent => {
cy.get('#input_upload_file').attachFile({
fileContent,
fileName,
mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
encoding:'utf8',
lastModified: new Date().getTime()
})
})
// wait for the 'upload_endpoint' request, and leave a 2 minutes delay before throwing an error
cy.wait('@upload', { requestTimeout: 120000 });
// stop watching requests
cy.server({ enable: false })
// keep testing the app
// e.g. cy.get('.link_file[aria-label="upload_1"]').contains('(xlsx)');
There is a set of recipes that demonstrates some framework setups along with different test cases. Make sure to check it out when in doubt.
Exposed command in a nutshell:
cySubject.attachFile(fixture, processingOpts);
Familiar with TypeScript? It might be easier for you to just look at type definitions.
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:
filePath
- file path (with extension)fileName
- the name of the file to be attached, this allows to override the name provided by filePath
fileContent
- the binary content of the file to be attachedmimeType
- file MIME type. By default, it gets resolved automatically based on file extension. Learn more about mimeencoding
- 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 herelastModified
- The unix timestamp of the lastModified value for the file. Defaults to current time. Can be generated from new Date().getTime()
or Date.now()
processingOpts
contains following properties:
subjectType
- target (aka subject) element kind: 'drag-n-drop'
component or plain HTML 'input'
element. Defaults to 'input'
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
allowEmpty
- when true, do not throw an error if fileContent
is zero length. Defaults to false
There is a set of recipes that demonstrates some framework setups along with different test cases. Make sure to check it out when in doubt.
Any contributions are welcome!
During the lifetime plugin faced some issues you might need to be aware of:
cy.trigger
) should happen when you use hidden HTML controls: #41Here is step-by-step guide:
encoding
property (see API)encoding
You have an idea of improvement, or some bugfix, or even a small typo fix? That's :cool:
We really appreciate that and try to share ideas and best practices. Make sure to check out CONTRIBUTING.md before start!
Have something on your mind? Drop an issue or a message in Discussions.
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!
FAQs
A Cypress command for file upload
The npm package cypress-file-upload receives a total of 626,643 weekly downloads. As such, cypress-file-upload popularity was classified as popular.
We found that cypress-file-upload demonstrated a not healthy version release cadence and project activity because the last version was released a year ago.Β It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.