2

How to select files from a local computer and upload to the website using cypress?

1
  • Any one can let me know that how we can upload the simple image file into cypress code.
    – user41641
    Commented Sep 24, 2019 at 4:50

3 Answers 3

2

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.

1

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

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.