Gathering detailed insights and metrics for cypress-file-upload
Gathering detailed insights and metrics for cypress-file-upload
Gathering detailed insights and metrics for cypress-file-upload
Gathering detailed insights and metrics for cypress-file-upload
npm install cypress-file-upload
55.1
Supply Chain
80.9
Quality
71.9
Maintenance
100
Vulnerability
96.7
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
498 Stars
528 Commits
90 Forks
9 Watching
3 Branches
30 Contributors
Updated on 28 Aug 2024
JavaScript (91.11%)
HTML (8.89%)
Cumulative downloads
Total Downloads
Last day
-12.5%
183,941
Compared to previous day
Last week
-0.4%
998,497
Compared to previous week
Last month
7.4%
4,440,608
Compared to previous month
Last year
-10.3%
50,651,652
Compared to previous year
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
:
1npm install --save-dev cypress-file-upload
If you are using TypeScript, ensure your tsconfig.json
contains commands' types:
1"compilerOptions": { 2 "types": ["cypress", "cypress-file-upload"] 3}
To be able to use any custom command you need to add it to cypress/support/commands.js
like this:
1import 'cypress-file-upload';
Then, make sure this commands.js
is imported in cypress/support/index.js
(it might be commented):
1// Import commands.js using ES2015 syntax: 2import './commands';
All set now! :boom:
Now, let's see how we can actually test something. Exposed command has signature like:
1cySubject.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.
1cy.get('[data-cy="file-input"]') 2 .attachFile('myfixture.json');
1cy.get('[data-cy="dropzone"]') 2 .attachFile('myfixture.json', { subjectType: 'drag-n-drop' });
1cy.get('[data-cy="file-input"]') 2 .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.
1cy.get('[data-cy="file-input"]') 2 .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:
1const special = 'file.spss'; 2 3cy.fixture(special, 'binary') 4 .then(Cypress.Blob.binaryStringToBlob) 5 .then(fileContent => { 6 cy.get('[data-cy="file-input"]').attachFile({ 7 fileContent, 8 filePath: special, 9 encoding: 'utf-8', 10 lastModified: new Date().getTime() 11 }); 12 });
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:
1cy.fixture('file.spss', 'binary') 2 .then(Cypress.Blob.binaryStringToBlob) 3 .then(fileContent => { 4 cy.get('[data-cy="file-input"]').attachFile({ 5 fileContent, 6 fileName: 'whatever', 7 mimeType: 'application/octet-stream', 8 encoding: 'utf-8', 9 lastModified: new Date().getTime(), 10 }); 11 });
1cy.get('[data-cy="file-input"]') 2 .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:
1cy.get('[data-cy="file-input"]') 2 .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:
1// start watching the POST requests 2cy.server({ method:'POST' }); 3// and in particular the one with 'upload_endpoint' in the URL 4cy.route({ 5 method: 'POST', 6 url: /upload_endpoint/ 7}).as('upload'); 8 9 10const fileName = 'upload_1.xlsx'; 11 12cy.fixture(fileName, 'binary') 13 .then(Cypress.Blob.binaryStringToBlob) 14 .then(fileContent => { 15 cy.get('#input_upload_file').attachFile({ 16 fileContent, 17 fileName, 18 mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 19 encoding:'utf8', 20 lastModified: new Date().getTime() 21 }) 22 }) 23 24// wait for the 'upload_endpoint' request, and leave a 2 minutes delay before throwing an error 25cy.wait('@upload', { requestTimeout: 120000 }); 26 27// stop watching requests 28cy.server({ enable: false }) 29 30// keep testing the app 31// 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:
1cySubject.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!
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
SAST tool detected but not run on all commits
Details
Reason
Found 3/15 approved changesets -- score normalized to 2
Reason
dependency not pinned by hash detected -- score normalized to 2
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
75 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More