Cypress has a built-in way for you to select files in an HTML5 input element and simulate dragging files into the browser with the introduction of the .selectFile()
command.
HTML5 input file upload
With the .selectFile()
command, you can easily select a fixture file in a form element:
cy.get('input[type=file]').selectFile('file.json')
Or multiple fixture files, as long as the file input has the multiple
property:
cy.get('input[type=file]').selectFile(['file.json', 'file2.json'])
You can also select a file created dynamically inside of a test, using the new Cypress.Buffer
utility:
cy.get('input[type=file]').selectFile({
contents: Cypress.Buffer.from('file contents'),
fileName: 'file.txt',
lastModified: Date.now(),
})
Dragging files into the browser
The .selectFile()
command also allows you to simulate dragging and dropping a file over an element, using the drag-drop
action:
cy.get('input[type=file]').selectFile('file.json', {
action: 'drag-drop'
})
And you can drop a file over the document:
cy.document().selectFile('file.json', { action: 'drag-drop' })
Manipulating binary data with Buffer
Cypress exposes an API for manipulating binary data, similar to the nodejs Buffer
class, as Cypress.Buffer
.
Not only are instances of Cypress.Buffer
accepted by .selectFile()
to specify files inline, but the cy.readFile()
and cy.fixture()
commands yield instances of Cypress.Buffer
when the encoding
is set to null
:
cy.readFile('images/logo.png', null).then((file) => {
// file will be read as a buffer
// and should look something like this:
// Buffer([0, 0, ...])
expect(Cypress.Buffer.isBuffer(file)).to.be.true
})
cy.fixture('images/logo.png', null).then((logo) => {
// logo will be read as a buffer
// and should look something like this:
// Buffer([0, 0, ...])
expect(Cypress.Buffer.isBuffer(logo)).to.be.true
})
Migrating from the cypress-file-upload plugin
The .selectFile()
command replaced the cypress-file-upload community plugin by Paul Auramenka, and moving forward we recommend that you update your tests to use the new command.
In order to streamline this process, a comprehensive Migration guide has been written which explains the exact steps you need to take to update existing tests to use .selectFile()
.
Resources
Cypress wants to hear from you!
The Cypress team has been working hard to deliver this improved experience. We're excited to bring APIs like .selectFile()
and Cypress.Buffer
to our users, and as always, we're eager to hear your feedback.
You can submit an issue on Github or chat with us on our Discord. Thanks for your support, and happy testing!
Join the flourishing Cypress community and elevate your testing skills to unprecedented levels! Engage with a vibrant network of like-minded professionals, exchange valuable insights, and stay abreast of the cutting-edge trends in component testing.