How to select files from a local computer and upload to the website using cypress?
3 Answers
Cypress does not support file upload out of the box. However there are several workaround that might or might not work for your particular case. You can observe the official cypress github discussion where people suggest their workarounds for your issue.
Cypress does not currently support native browser events such as filepicker, however, it is on their roadmap. native browser events The workaround is to add files to your fixture folder and then to create a custom command like
Cypress.Commands.add(
'dropFile', {
prevSubject: false
}, (fileName) => {
Cypress.log({
name: 'dropFile',
})
return cy
.fixture(fileName, 'base64')
.then(Cypress.Blob.base64StringToBlob)
.then(blob => {
// instantiate File from `application` window, not cypress window
return cy.window().then(win => {
const file = new win.File([blob], fileName)
const dataTransfer = new win.DataTransfer()
dataTransfer.items.add(file)
return cy.document().trigger('drop', {
dataTransfer,
})
})
})
}
)
Then in your tests, you can do something like:
it('Uploads a CSV', () => {
cy.document().trigger('dragenter')
// you don't need to use cy.document() that is where my event listener is.
//you could use cy.get('element').trigger('dragenter')
cy.dropFile('test.csv')
})
Or you can use the plugin published and listed on the Cypress plugins page: Cypress.io Plugin Page Direct link here drag and drop repo
You can select out one of the fixtures present in project and pass it to your file unput via: https://www.npmjs.com/package/cypress-file-upload
After that you need to submit a form (or start uploading in any other way), but that's details related to your specific case.