cypress upload image code example

Example 1: upload image cypress

// programmatically upload the logo
cy.fixture('images/logo.png').as('logo')
cy.get('input[type=file]').then(function($input) {
  // convert the logo base64 string to a blob
  return Cypress.Blob.base64StringToBlob(this.logo, 'image/png')
    .then((blob) => {
      // pass the blob to the fileupload jQuery plugin
      // used in your application's code
      // which initiates a programmatic upload
      $input.fileupload('add', { files: blob })
    })
})

Example 2: upload photos cypress

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')
})

Example 3: upload photos cypress

cy.fixture('path/to/image.png').as('logo')
  .get('input[type=file]').then(function(el) {
    return Cypress.Blob.base64StringToBlob(this.logo, 'image/png')
      .then(blob => {
        el[0].files[0] = blob
        el[0].dispatchEvent(new Event('change', {bubbles: true}))
      })
  })

Example 4: upload photos cypress

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,
                    })
                })
            })
    }
)