Cypress 9.3.0 added .selectFile() command to select files


Cypress is a great tool that enables us to write faster, easier, and more reliable tests. It comes with a lot of features such as time travel, automatic waiting, network traffic control and cross-browser testing.

However, since it’s a relatively new package, it also has multiple limitations and one of those is that it doesn’t support native file upload. Cypress 9.3.0 has introduced a .selectFile() command to select files in an HTML5 input element and simulate dragging files into the browser.

Syntax

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

Usage

cy.get('input[type=file]').selectFile('file.json')
cy.document().selectFile('file.json', { action: 'drag-drop' })

Dragging files into the browser

Before version 9.3.0 cypress-file-upload NPM package was used to upload a file in Cypress. The .selectFile() draws inspiration from the cypress file upload plugin.

From version 9.3.0 we can simulate dragging and dropping a file over an element, using the ‘drag-drop’ action.

cy.get('input[type=file]').selectFile('sample.json', {
  action: 'drag-drop'
})

Migration

The .selectFile() command replaces the cypress-file-upload plugin and it is recommended to update the tests to use the new command.

Migration guide has been written to help in updating existing tests to use .selectFile().

To know more about this, check out the PR.

Join Our Newsletter