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

其他-如何使用cypress触发filepond上传?

(其他 - How can I trigger filepond uploads using cypress?)

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

我正在尝试使用cypress为使用Vue Filepond处理上传的媒体应用程序编写e2e测试,但是在触发文件上传时遇到了麻烦。我怎样才能做到这一点?

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

经过一番搜索之后,我发现了这个由github用户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');
        });
      });
  });
});

它成功了。将其放在测试文件之上之后,我可以简单地编写

cy.uploadFile("input[type=file]", "some-audio-file.wav", "audio/wav")

并触发了上传