Cypress selectFile Command

Profile picture for user arilio666

selectFile command in cypress selects/uploads files in an HTML5 input element, or it can also simulate dragging a file/files into the browser.

Syntax:

.selectFile(file)
.selectFile(file, options)
.selectFile([file1, file2, ...])
.selectFile([file1, file2, ...], options)

Arguments Used In SelectFile:

File: Can contain the path to the file, alias of the stored path, etc.

Options:

Action: default is 'select' switches modes valid are select and drag-drop.
animationDistanceThreshold: The default is 'animationDistanceThreshold' distance in the pixel element must exceed over time to be considered animating.
Force: default is false. It forces an action.
Log: default is true and displays the command in the command log.
Timeout: default is 'defaultCommandTimeout' time to wait for selectFile to resolve.
waitForAnimations: default is 'waitForAnimations ' waits for elements to finish animating before proceeding to the next step.

Correct Usage:

cy.get('input[type=file]').selectFile('file.png')

Wrong Usage:

cy.selectFile('file.png')

Example:

  • To demonstrate how selectFile works, we will upload a file using the command in the autopract site.
  • Here's a file G.png in our fixture location that will be used to upload.
describe('Automate AutoPract',()=>{

   it('Upload File Using SelectFile Command',()=>{
     

       cy.visit('http://www.autopract.com/#/home/fashion')
       cy.get("button[aria-label='Close'] ").click()
       cy.get('.btn.btn-success').scrollIntoView()
       
       cy.get('input[type="file"]').selectFile('cypress/fixtures/G.png', {force:true})





       })
   })
  • There it works flawlessly by uploading the file using the selectFile command. This is one way of doing this, and there are multiple ways files can be uploaded using this command.

Yield:

  • .selectFile() yields the same subject it's been given in the previous command.

Rules:

selectFile must be chained off with a command that yields DOM elements.
The file must exist within the provided path.
If provided with an alias, it must not be null or undefined.
selectFile waits for elements to reach the actionable state.