我正在尝试使用cypress为使用Vue Filepond处理上传的媒体应用程序编写e2e测试,但是在触发文件上传时遇到了麻烦。我怎样才能做到这一点?
经过一番搜索之后,我发现了这个由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")
并触发了上传
这对我来说是一个错误,因为输入已被覆盖
filepond--drop-label
但已更改.trigger('change');
为.trigger('change', { force: true });
固定(如果其他人有此问题)。