Warm tip: This article is reproduced from serverfault.com, please click

How can I trigger filepond uploads using cypress?

发布于 2020-12-10 12:00:37

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?

Questioner
Bossan
Viewed
0
Bossan 2020-12-11 00:46:43

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.