I'm trying to use cypress for writing e2e tests for a media application that handles uploads using Vue Filepond, but I have trouble triggering the file uploads. How can I do this?
Asked
Active
Viewed 401 times
1 Answers
2
After a fair bit of searching I found this code snippet posted by github user DragorWW
Cypress.Commands.add("uploadFile", (selector, fileUrl, type = "") => {
return cy.get(selector).then(subject => {
return cy
.fixture(fileUrl, "base64")
.then(Cypress.Blob.base64StringToBlob)
.then(blob => {
return cy.window().then(win => {
const el = subject[0];
const nameSegments = fileUrl.split("/");
const name = nameSegments[nameSegments.length - 1];
const testFile = new win.File([blob], name, { type });
const dataTransfer = new DataTransfer();
dataTransfer.items.add(testFile);
el.files = dataTransfer.files;
return cy.wrap(subject).trigger('change');
});
});
});
});
and it did the trick. After putting it on top of my test file I could simply write
cy.uploadFile("input[type=file]", "some-audio-file.wav", "audio/wav")
and the upload got triggered.

t-bone
- 184
- 2
- 14
-
1This threw an error for me because the input is covered by `filepond--drop-label` but changing `.trigger('change');` to `.trigger('change', { force: true });` fixed it (if anyone else has this issue). – edant92 Mar 15 '21 at 16:10