Search code examples
file-uploaduploadcypresscypress-file-upload

Uploading a file in Cypress when no input type="file"


I need to upload a file, but the thing is that the button doesn't have the tag input and attr type="file". How do I solve this? The DOM: enter image description here

I tried:

cy.contains('div#dropdown-grouped', "Bon d'intervention").siblings('div.d-none').find('input[type="file"]') 
    .selectFile('cypress/fixtures/bon.pdf', {force: true})

But this returns a statusCode 422

Also tried:

const filePath = 'My reportis.jpg'
    cy.contains('#dropdown-group-1', "Bon d'intervention").attachFile(filepath)

But this obviously does nothing.

What if I would change the tag of the button from button to input, and add an attr type="file", would that work? If yes, how do you I change the tag with cypress?

Thank you very much!

Solution:

cy.contains('#dropdown-group-1', "Bon d'intervention").click()
cy.get('input[type="file"]').selectFile('cypress/fixtures/bon.pdf', {force: true})

Solution

  • Your first code is correct,

    cy.contains('div#dropdown-grouped', "Bon d'intervention")
      .siblings('div.d-none')
      .find('input[type="file"]')
      .selectFile('cypress/fixtures/Call order.pdf', {force: true})
    

    Status code 422 is a response from the server, so selectFile() worked and the app fired a POST, but the server did not like what it was given.

    422 Unprocessable Entity

    The HyperText Transfer Protocol (HTTP) 422 Unprocessable Entity response status code indicates that the server understands the content type of the request entity, and the syntax of the request entity is correct, but it was unable to process the contained instructions.


    From further discussion, it looks like following the steps a user takes gives a working test, which means adding a button click() before the selectFile().

    This is the final working test:

    cy.contains('#dropdown-group-1', "Bon d'intervention").click() 
    
    cy.get('input[type="file"]')
      .selectFile('cypress/fixtures/bon.pdf', {force: true})