Skip to content

Instantly share code, notes, and snippets.

@SergioMendolia
Created January 31, 2019 09:45
Show Gist options
  • Save SergioMendolia/6cd884d2f81f3cfa13c6e988da61b4b7 to your computer and use it in GitHub Desktop.
Save SergioMendolia/6cd884d2f81f3cfa13c6e988da61b4b7 to your computer and use it in GitHub Desktop.
Allow to chain commands to fill an input file in cypress

usage

    cy.get('input[type=file]').selectFile('testDocument.pdf');
function getFixtureBlob(fileUrl, type = 'application/pdf') {
return cy.fixture(fileUrl, 'base64').then(Cypress.Blob.base64StringToBlob);
}
Cypress.Commands.add('selectFile', { prevSubject: true },
(selector, fileUrl) => {
const obj = cy.wrap(selector);
return obj.then(subject => {
return getFixtureBlob(fileUrl).then(blob => {
return cy.window().then(win => {
const name = fileUrl.split('/').pop();
const testFile = new win.File([blob], name, { type: blob.type });
const dataTransfer = new win.DataTransfer();
dataTransfer.items.add(testFile);
const el = subject[0];
el.files = dataTransfer.files;
return subject;
});
});
});
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment